use of org.exist.indexing.sort.SortItem in project exist by eXist-db.
the class CreateOrderIndex method eval.
@Override
public Sequence eval(final Sequence[] args, final Sequence contextSequence) throws XPathException {
if (args[1].isEmpty())
return Sequence.EMPTY_SEQUENCE;
final String id = args[0].getStringValue();
// check how the function was called and prepare callback
FunctionReference call = null;
if (isCalledAs("create-index-callback")) {
call = (FunctionReference) args[2].itemAt(0);
} else if (args[2].getItemCount() != args[1].getItemCount())
throw new XPathException(this, "$nodes and $values sequences need to have the same length.");
// options
if (args[3].getItemCount() > 0) {
final NodeValue optionValue = (NodeValue) args[3].itemAt(0);
final Element options = (Element) optionValue.getNode();
String option = options.getAttribute("order");
if (option != null) {
descending = option.equalsIgnoreCase("descending");
}
option = options.getAttribute("empty");
if (option != null) {
emptyLeast = option.equalsIgnoreCase("least");
}
}
// create the input list to be sorted below
final List<SortItem> items = new ArrayList<>(args[1].getItemCount());
final Sequence[] params = new Sequence[1];
SequenceIterator valuesIter = null;
if (call == null)
valuesIter = args[2].iterate();
int c = 0;
final int len = args[1].getItemCount();
final int logChunk = 1 + (len / 20);
for (final SequenceIterator nodesIter = args[1].iterate(); nodesIter.hasNext(); ) {
final NodeValue nv = (NodeValue) nodesIter.nextItem();
if (nv.getImplementationType() == NodeValue.IN_MEMORY_NODE)
throw new XPathException(this, "Cannot create order-index on an in-memory node");
final NodeProxy node = (NodeProxy) nv;
final SortItem si = new SortItemImpl(node);
if (LOG.isDebugEnabled() && ++c % logChunk == 0) {
LOG.debug("Storing item {} out of {} to sort index.", c, len);
}
if (call != null) {
// call the callback function to get value
params[0] = node;
final Sequence r = call.evalFunction(contextSequence, null, params);
if (!r.isEmpty()) {
AtomicValue v = r.itemAt(0).atomize();
if (v.getType() == Type.UNTYPED_ATOMIC)
v = v.convertTo(Type.STRING);
si.setValue(v);
}
} else {
// no callback, take value from second sequence
AtomicValue v = valuesIter.nextItem().atomize();
if (v.getType() == Type.UNTYPED_ATOMIC)
v = v.convertTo(Type.STRING);
si.setValue(v);
}
items.add(si);
}
// sort the set
FastQSort.sort(items, 0, items.size() - 1);
// create the index
final SortIndexWorker index = (SortIndexWorker) context.getBroker().getIndexController().getWorkerByIndexId(SortIndex.ID);
try {
index.createIndex(id, items);
} catch (final EXistException e) {
throw new XPathException(this, e.getMessage(), e);
} catch (final LockException e) {
throw new XPathException(this, "Caught lock error while creating index. Giving up.", e);
}
return Sequence.EMPTY_SEQUENCE;
}
Aggregations