Skip to content

Read a mixed index of the order keys which answers a query whole - #5125

Merged
porunov merged 1 commit into
JanusGraph:masterfrom
porunov:order-by-key-reads-its-mixed-index
Oct 24, 2026
Merged

porunov merged 1 commit into
JanusGraph:masterfrom
porunov:order-by-key-reads-its-mixed-index

Conversation

@porunov

@porunov porunov commented Oct 23, 2026 •

Copy link
Copy Markdown
Member

Fixes #5124

Merge after #5127, which reads a Solr result larger than a page in pages which grow up to index.[X].solr.max-page-size, rather than in pages of 50 at growing offsets: the Cost note below has the figures.

Since #5108, a traversal's order().by(key) leaves out the elements which have no value of the key, so g.V().order().by('name').limit(10) returns what g.V().has('name').order().by('name').limit(10) returns. JanusGraph answers the second from the mixed index which holds name, sorted by the index, and reads only the first hits. It answered the first, which has no condition that an index answers, by reading every vertex and sorting them in memory. That fails with a QueryException from a million vertices on, and query.force-index refuses it as a full scan. So did g.V().hasLabel('person').order().by('name').limit(10) with an index of the persons which holds name, and an order of edges by a key of an edge mixed index.

Such a traversal now reads a single mixed index which holds every order key, which its backend sorts by, and answers every condition, as has(key) does: fitted, and, with JanusGraph's index selection strategies, sorted by the index, so that a limit reads only the first hits. Every other traversal reads what it read before.

Changes

  • GraphCentricQueryBuilder.constructQueryWithoutProfile: where the index selection strategy chooses no index for the query's own conditions, and the query requires the values of its order keys (requireOrderValues(), which JanusGraphStep calls), the strategy chooses again for those conditions together with the presence of a value of each order key, PredicateCondition(key, Cmp.NOT_EQUAL, null).
    • Candidates (sortingIndexes): the builder passes the strategy's selectIndices(Set<IndexType> indexCandidates, …) the mixed indexes of the result type which hold a key of a condition (IndexSelectionUtil.getMatchingIndexes, as AbstractIndexSelectionStrategy.createIndexRawCandidates finds a strategy's own candidates), and which sort the elements by the query's order:

      • they hold every order key, which their backend sorts by as JanusGraph orders its values, a key of several values included (IndexSelectionUtil.indexCoversOrder, which asks each backend through IndexSerializer.supportsOrdering since Sort in memory the orders by keys which the index backend can't sort #5121): no backend sorts by a string which the index maps as TEXT, as a mixed index maps a string by default, Elasticsearch doesn't by a string with a string-analyzer, and Lucene doesn't by a UUID, nor by a key of LIST or SET cardinality;
      • they hold none of the order keys with custom parameters (holdsNoOrderKeyWithCustomParameters), which Elasticsearch takes into its mapping, and which may keep it from sorting by the key, as doc_values false does: supportsOrdering doesn't look at them.

      The brute-force strategy, the default's choice up to query.index-select-threshold candidates, weighs an index which holds a key as a TEXT as one which holds it as a STRING, and breaks the tie by the order of a HashSet of new IndexCandidates, which differs from one query to the next: left among the candidates, the TEXT index would be taken in place of one which holds the key as a STRING or a TEXTSTRING, by chance, where both answer the query alike. The approximate strategy, the default's choice beyond that threshold, prefers the one which sorts, as it scores an index which covers the order higher (ORDER_MATCH), by indexCoversOrder, which asks supportsOrdering since Sort in memory the orders by keys which the index backend can't sort #5121. An index which holds only some of the order keys isn't a candidate, as no such index could be the single one which answers the query. The composite indexes which a strategy's own candidates hold are left out too: they can't answer the presence of a key, so that a choice with one isn't a single index which covers every condition. The filter of createIndexRawCandidates for an or() alone doesn't apply, as these conditions are a conjunction.

    • The query takes that choice where it is a single index which covers every condition (coveredWithValues.size() == withValues.numChildren()), and so a mixed index which holds every order key and answers the query whole, and where that index is one of the candidates (candidates.contains(…)): IndexSelectionStrategy doesn't promise to choose among them, and a strategy which takes another index may take one which can't sort by the order keys, whose every hit JanusGraph would then read and sort, or one which holds a key with custom parameters, which the index is given the order by and may fail on, as Elasticsearch fails with Could not call index on doc_values false. Such a choice leaves the order to the scan, so that every second choice is one which the index can sort.

      • The query is fitted, and sorted where the index sorts by the query's order, as it does with JanusGraph's strategies (sortedOnlyWhereTheIndexSorts checks it), so that a limit reads only the first hits. A strategy which gives the index only part of the order, as the test's PartialOrderIndexSelectionStrategy does, gets a fitted choice which the index doesn't sort, and JanusGraph sorts its hits itself, with the right results.
      • A count() right after the order, or a min(), max(), sum() or mean() of a key which the index holds, comes from the index (JanusGraphMixedIndexCountStrategy and JanusGraphMixedIndexAggStrategy), as after a has().
      • The strategies decide, as for a has(key), whether a mixed index covers such a condition (AbstractIndexSelectionStrategy.coversAll: an ENABLED field of the key, and IndexSerializer.supportsExistsQuery), and take an index restricted to a label only for a query of that label, whose condition the index then covers too.
    • A custom strategy keeps its choice among the candidates, as the test strategy which gives the index only part of the order does through that method. For this choice, it loses an override of createIndexRawCandidates and any override of selectIndices(ElementCategory resultType, …): the builder doesn't call them, and gives the candidates itself. A choice of an index which isn't among them is refused, as above.

  • Where nothing changes:
    • The first choice found an index: as before, the presence conditions don't take part in choosing, so that a mixed index which holds an order key isn't read whole next to a composite index which answers the other conditions. A mixed index chosen for the other conditions takes them where it holds the key (requireValues).
    • The second choice leaves a condition to JanusGraph, as one on a key which no index holds, has('tag', 't'), or the label of hasLabel('person') for an index which isn't restricted to persons. The query would read the index in growing batches, looking each element up to check the condition, up to every element with a value of the order keys where few hold the condition; the scan reads every element once, in the storage backend's order.
    • Only several indexes together answer the query. Every candidate holds every order key, so that g.V().hasLabel('person').order().by('nick').by('name'), with nick in an index of the persons and name in another one, has none, and with both in an index which isn't restricted to persons next to the index of the persons, only the first, which leaves the label to JanusGraph. Two candidates still answer a query only together where each covers the presence of some of the keys alone, as where each holds one of them in a field which isn't ENABLED, and a custom strategy may take several of them. A joint query streams its first subquery and reads every other one whole: StandardJanusGraphTx's executor passes Query.NO_LIMIT to QueryUtil.processIntersectingRetrievals, which collects each into a list. A single mixed index which holds every order key, restricted to the traversal's label where it has one, answers such an order.
    • An or() alone: JanusGraphStep runs each of its branches as a query of its own where no index answers the or() whole, and each branch chooses again itself. No index covers the or() in the second choice where none covers it in the first, so that split stays as it was, and each branch takes the second choice on its own where a single mixed index answers it whole. Several or() steps make a conjunction, which JanusGraphStep runs as a single query, and which takes the second choice as a whole where a single mixed index answers each of them.
    • No index which holds the order keys has a backend which sorts by them as JanusGraph orders their values, or none holds them without custom parameters: as for an order by a string with the default mapping, by a UUID on Lucene, or of edges by a key of LIST or SET cardinality on Lucene, which now keeps the scan.
    • A query of JanusGraph's API, which keeps the elements without the key and calls no requireOrderValues().
  • requireOrderValues()'s Javadoc says where the presence conditions take part in choosing the indexes.
  • Docs: the Ordering section of the index performance page says that such an order reads a mixed index which holds every order key and answers the traversal's conditions, how a label restriction applies, which indexes it leaves out, and where it reads every element.
  • Changelog: a section after Ordered traversals leave out the elements which have no value of an order key. It says that these traversals now see what a has(key) sees, as an index does, rather than what the storage backend holds, both ways; that on Elasticsearch such a traversal without a limit reads every hit in pages of max-result-set-size, and on Solr in the growing pages of Read Solr results larger than a page in growing pages #5127's section; and Orders by a key of several values now points to it where a mixed index holds the key.

Tests

  • JanusGraphIndexTest.testOrderReadsAMixedIndexOfItsKeysWhereNoIndexAnswersTheConditions (every index backend; the mixed indexes are named mixed, vertices and edges, which the Solr test container creates). Persons, organizations and other vertices, most of them without a name, an age, a nick or a tag, and edges between them, some without a weight, are written into the graph and into a TinkerGraph. mixed holds the names, ages and ckinds of every vertex, vertices the nicks of the persons only (indexOnly), edges the weights. Composite indexes hold ckind, which a query of a ckind reads rather than mixed, and uid. No index holds tag. Twenty-eight traversals return the same from both:

    • orders by name, ascending and descending, with limits and a range, and a count() after the order;
    • orders by age and name, which mixed holds, the second ordering the ties of the first;
    • an order by name and tag, which no index holds;
    • orders by tag, by weight, which only the index of edges holds, and by nick without the label, and of persons and organizations, or organizations only, by nick;
    • orders of persons by nick, which vertices answers whole, also with a count(), by name, which mixed answers but for the label, and by nick and name, which only both indexes together hold;
    • orders next to has('tag') and has('tag', gt('t3')), which no index answers;
    • orders next to conditions which a composite index answers: has('ckind', 'p'), has('ckind', within('p', 'q')), and or(has('ckind', 'p'), has('uid', 8));
    • an order next to or(has('tag', gt('t5')), has('ckind', 'q')), of which no index answers the first branch, and one next to two or() steps which no index answers;
    • orders of edges by weight, also of the label link with a count().

    They return the same again in a transaction which adds a person, an organization and another vertex, gives a vertex a name and takes another one's, changes a name and a nick, takes a nick, removes a vertex, and adds an edge, removes one, changes a weight, takes one and gives one. A new transaction's profiles show:

    • [(name <> null)][ASC(name)]:mixed, fitted and sorted, for order().by('name').limit(3), [DESC(name)] descending, and [(age <> null AND name <> null)][ASC(age), ASC(name)]:mixed for the two keys;
    • [(nick <> null)][ASC(nick)]:vertices, fitted and sorted, for the persons by nick;
    • [(weight <> null)][ASC(weight)]:edges, fitted and sorted, for the edges;
    • the index's aggregation step (JanusGraphMixedIndexAggStep) for order().by('name').count(), and for order().by('name').values('age') and min(), max(), sum() and mean(), which return what the TinkerGraph returns;
    • a full scan where mixed would leave a condition to JanusGraph: for the order by name and tag, the persons by name, and has('tag') by name;
    • a full scan for the persons by nick and name, for the orders by tag, by weight and by nick without the label, and for organizations or persons and organizations by nick;
    • the composite index alone, unsorted, for has('ckind', 'p') and within, and for each of the two branches of the or(), which run as queries of their own;
    • a full scan for the branch has('tag', gt('t5')), which no index answers, and the composite index for the other branch, and a full scan for the two or() steps, which make a single query.
  • JanusGraphIndexTest.testForceIndexAllowsAnOrderWhichAMixedIndexOfItsKeysAnswers (every index backend): with query.force-index, six traversals which a mixed index answers, or a composite one, return what the TinkerGraph returns, and four which read every vertex, has('tag').order().by('name') among them, fail with Could not find a suitable index.

  • JanusGraphIndexTest.testOrderReadsAMixedIndexOfItsKeysOnlyWhereItsBackendSortsByThem (every index backend). mixed holds a name, a text with the default mapping, words mapped as TEXT, a title mapped as TEXTSTRING, an analyzed string mapped as STRING with a string-analyzer, and a UUID code, and gets a rank added after the vertices were written, which isn't ENABLED. vertices holds rank and gets name added in the same way, so that only the two indexes together answer the presence of both. Six orders by text, words, name and text, rank and name, and name and rank return what a TinkerGraph returns, by a full scan; the texts' least words don't order them as their strings do, as Solr would. Orders by name, and by title ascending and descending, read mixed, sorted, and return what the TinkerGraph returns: Mango, apple, x a, which neither the titles' lower case nor their least words order so. The orders by analyzed and by code read mixed, sorted, where its backend sorts by the key, as the graph's IndexSerializer.supportsOrdering tells, and every vertex otherwise: Lucene and Solr read it for analyzed, which Elasticsearch scans for, and Elasticsearch and Solr for code, which Lucene scans for. The codes, of which the first digit of either half is from 8 up or below it, come in the order of their string forms, as JanusGraph orders UUIDs, which isn't TinkerPop's UUID.compareTo order.

  • JanusGraphIndexTest.testOrderByAKeyOfTwoMixedIndexesReadsTheOneWhichSortsByIt (every index backend): mixed holds name as a TEXT, and vertices as a STRING, both of every vertex. mixed is built first, and its name sorts first, so that a strategy which broke the tie by either order would take it every time, and the default's brute-force choice would take it now and then. Twenty times, order().by('name').limit(3) is built anew, returns what a TinkerGraph returns, and reads vertices, fitted and sorted.

  • JanusGraphIndexTest.testOrderReadsEveryElementWhereTheStrategyTakesAnIndexOutsideItsCandidates (every index backend): the same indexes, with CandidateIgnoringIndexSelectionStrategy, a test strategy which chooses among the indexes that match the conditions other than its candidates, where there are any, as one which collects indexes of its own might. It takes mixed, which the builder refuses: order().by('name').limit(3) returns what a TinkerGraph returns, by a full scan.

  • ElasticsearchJanusGraphIndexTest.testOrderByAKeyWhichElasticsearchMayNotSortByReadsEveryElement (Elasticsearch): orders by a STRING key and a TEXTSTRING key with a string-analyzer, and by a STRING key with the custom parameter doc_values false, ascending and descending, also after a STRING key which Elasticsearch sorts by, return their values in order, by a full scan.

  • JanusGraphIndexTest.testOrderingListProperty (from List property ordering - utilize mixed index #4860) expected g.V().order().by('name1') to read every vertex. It now reads listPropertyOrdering with (name1 <> null), sorted, and so does g.V().order().by('name2'), of a LIST key, on Elasticsearch and Solr.

  • JanusGraphIndexTest.testResultsWhichAStrategyHoldsSortedByAnIndexGivenPartOfTheOrderAreSortedInMemory (from Order by a key of several values as the indexes do #5102): V().order().by('name').by('age'), which the second choice answers, returns the ages in order, ascending and descending, under the strategy which gives the index only the first key of the order.

  • JanusGraphIndexTest.testOrderOfEdgesByAKeyDeclaredToHoldSeveralValues (from Order by a key of several values as the indexes do #5102): g.E().order().by('weights'), of a LIST key, without a condition, returns the weights in order, ascending and descending, and reads edges, sorted, on Elasticsearch and Solr, which sort by a key of several values, and every edge on Lucene, which doesn't.

Mutations, each reverting or breaking one part of the change, are all caught (20, all run with Lucene; the two which only Elasticsearch catches with Elasticsearch 9.5.4 too; and those which drop indexCoversOrder from the filter, drop its check of supportsOrdering, drop the check of the candidates, or check the choice afterwards, with Elasticsearch and with Solr in the JVM too):

  • Master's GraphCentricQueryBuilder, without the second choice: the profile of order().by('name').limit(3) shows a full scan, [] for [(name <> null)][ASC(name)]:mixed, and so do testOrderingListProperty's index check, the order by name of the filter's test, and the test of the two indexes; under query.force-index, Could not find a suitable index to answer graph query and graph scans are disabled: [(name <> null)]3(3):VERTEX.
  • The second choice made whatever the first found: has('ckind', 'p') reads mixed, which then answers its condition and its order, mixed for byCkind.
  • The second choice taken where it leaves a condition to JanusGraph: under query.force-index, has('tag').order().by('name') is no longer refused, and the persons by name read mixed, null for a full scan.
  • Several indexes taken: order().by('rank').by('name') reads mixed and vertices together, each of which answers the presence of one of the keys: null for a full scan where vertices comes first in the joint query, and [4, 3, 2, 1] for [3, 1, 4, 2] where mixed does, sorting by its rank, which isn't ENABLED. So the rule of a single index keeps the order right, too.
  • The covered clauses of the second choice not kept: the presence is narrowed in again, [(name <> null AND name <> null)][ASC(name)]:mixed; and so it is where a covered presence is narrowed again.
  • The first choice's sortedness kept: isOrdered false.
  • No sortedOnlyWhereTheIndexSorts on the second choice: under the strategy which gives the index only the first order key, the ties of the name come in the index's order, as [3, 1, 2, 0] for [1, 2, 3, 0].
  • The second choice over the query's own conditions only: as on master.
  • No indexCoversOrder in the filter, with the check of custom parameters kept, or failing with a NullPointerException on an index which lacks an order key: the orders by text read mixed, null for a full scan, the key of the two indexes reads mixed unsorted, for [(name <> null)][ASC(name)]:vertices, and under the strategy which takes an index outside its candidates, which then has none to take, the order reads an index rather than every element, on Lucene, Elasticsearch and Solr; on Lucene, the edges by weights read edges. The same failing with a NullPointerException on an index which lacks an order key, no filter at all, or the strategy's own candidates in its place: caught alike, on Lucene.
  • indexCoversOrder without its check of IndexSerializer.supportsOrdering: the same failures but for the edges by weights, on Lucene, Elasticsearch and Solr.
  • indexCoversOrder without its rule for keys of several values: on Lucene, the edges by weights read edges, unsorted, null for a full scan.
  • No check of custom parameters, or of the first order key's only: Could not call index on Elasticsearch for the order by the key with doc_values false, alone or after a STRING key.
  • The filter applied to the strategy's choice afterwards, rather than to its candidates: the key of the two indexes is read by a full scan in one of the test's twenty runs, [] for [(name <> null)][ASC(name)]:vertices, on Lucene, Elasticsearch and Solr.
  • The choice taken although its index isn't one of the candidates: under the strategy which takes an index outside them, the order reads mixed, which holds name as a TEXT, unsorted, null for a full scan, on Lucene, Elasticsearch and Solr.
  • The indexes of other elements than the query's kept: g.V().order().by('weight') reads the index of edges, and fails with IllegalArgumentException: Id must be either String or a positive long value.

Three changes which shouldn't matter change no test's result: a check that the query isn't an or() alone, the composite indexes kept among the candidates, and the filter applied to the strategy's choice afterwards as well. A single index which covers every condition covers the presence of each order key, which a composite index can't, and covers an or() alone only where the first choice did; and the choice is one of the candidates.

On master c29f6f365, with these tests, on Lucene:

  • testOrderReadsAMixedIndexOfItsKeysWhereNoIndexAnswersTheConditions returns what TinkerGraph returns for its twenty-eight traversals, and then fails at its first profile check, a full scan: [] for [(name <> null)][ASC(name)]:mixed.
  • testForceIndexAllowsAnOrderWhichAMixedIndexOfItsKeysAnswers fails with JanusGraphException: Could not find a suitable index to answer graph query and graph scans are disabled: [(name <> null)]3(3):VERTEX.
  • testOrderReadsAMixedIndexOfItsKeysOnlyWhereItsBackendSortsByThem passes its six full scans, as master scans for every order, and fails where it expects the order by name to read the index, [] for [(name <> null)][DESC(name)]:mixed.
  • testOrderByAKeyOfTwoMixedIndexesReadsTheOneWhichSortsByIt returns what TinkerGraph returns, and fails where it expects the order to read vertices, [].
  • testOrderingListProperty fails its check that g.V().order().by('name1') reads the index.
  • testOrderReadsEveryElementWhereTheStrategyTakesAnIndexOutsideItsCandidates and testOrderOfEdgesByAKeyDeclaredToHoldSeveralValues pass, as master reads every element for those orders, and so does testResultsWhichAStrategyHoldsSortedByAnIndexGivenPartOfTheOrderAreSortedInMemory, as master sorts that order in memory.

The reproduction of the issue, run as a Java program with master's core and with this change's, gives the profiles and the query.force-index failure which the issue quotes on master, and on this change [(name <> null)][ASC(name)](2):byName, fitted and sorted, also under query.force-index. With 1,000,001 vertices, master fails g.V().order().by('name').limit(2) with QueryException: Could not execute query since pre-sorting requires fetching more than 1000000 elements. Consider rewriting the query to exploit sort orders, and this change returns the first two names.

Locally, Java 11, on this change as it stands, rebased on master c29f6f365, which has #5115, #5117, #5119, #5121 and #5123, with checkstyle (no violations):

  • janusgraph-driver (132), janusgraph-core (245), janusgraph-inmemory (717, 85 skipped), janusgraph-test (1,132), janusgraph-berkeleyje (399, 12 skipped) and janusgraph-lucene (475, 148 skipped) pass.
  • On Elasticsearch 9.5.4 in a container, BerkeleyElasticsearchTest whole passes (156, 1 skipped), with janusgraph-es's checkstyle.
  • On Solr 9.10.1 in the JVM, SolrRunner's MiniSolrCloud with BerkeleyJE as BerkeleySolrTest configures it, JanusGraphIndexTest whole passes (143, 1 skipped). The repository's janusgraph-solr/src/test/resources/collections.txt lacks listPropertyOrdering, which testOrderingListProperty needs: the harness ran with a copy which adds it, as CI's container lists it in JanusGraphSolrContainer.COLLECTIONS.
  • The twenty shapes of the timing harness return the same elements, in the same order, and the same counts, with master's core and with this change's, on Lucene and on Elasticsearch 9.5.4.
  • CQL and the other storage backends are left to CI, as are Solr and Elasticsearch in their CI containers.

Notes

  • Cost. An A/B of janusgraph-core against master c29f6f365, on an inmemory graph with its mixed indexes on Lucene, and in two more runs on Elasticsearch 9.5.4 and on Solr 9.10.1 in containers: 40,000 vertices, persons and organizations, a fifth of which lack a name, a fifth an age, a fifth a nick and a fifth a description, each drawn on its own, and 20,000 edges, a fifth without a weight. The mixed index mixed holds every vertex's name, mapped as STRING, its age and its description, mapped as TEXT by default; people holds the persons' nick, mapped as STRING, and edges the edges' weight; no index holds tag, which one vertex and one edge in a thousand have as rare, and none as none. The Solr run has Read Solr results larger than a page in growing pages #5127's janusgraph-solr on both sides, as the Solr paragraph below explains. Each group of traversals ran in JVMs of its own, three passes a side in alternating order, each figure the median of the passes' medians of three timed windows of 2 s after a warm-up, at 1 thread:

    Traversal Lucene: master this change Elasticsearch: master this change Solr: master this change
    g.V().order().by('name').limit(10) 572.8 ms 0.94 ms 569.6 ms 0.87 ms 594.1 ms 0.39 ms
    g.V().order().by('name', desc).limit(10) 576.9 ms 0.95 ms 566.1 ms 0.89 ms 596.1 ms 0.37 ms
    g.V().order().by('age').by('name').limit(10) 982.2 ms 1.19 ms 969.7 ms 0.60 ms 1015.5 ms 0.39 ms
    g.V().order().by('name').range(100, 110) 572.8 ms 2.66 ms 568.8 ms 2.43 ms 601.0 ms 0.81 ms
    g.V().hasLabel('person').order().by('nick').limit(10) 594.2 ms 0.75 ms 579.0 ms 0.79 ms 604.4 ms 0.36 ms
    g.V().order().by('name').count() 604.1 ms 0.97 ms 604.5 ms 0.41 ms 617.9 ms 0.35 ms
    g.E().order().by('weight').limit(10) 71.6 ms 0.61 ms 73.2 ms 0.57 ms 74.1 ms 0.43 ms
    g.V().order().by('name').range(20000, 20010) 606.3 ms 102.5 ms 596.9 ms 314.3 ms 600.7 ms 193.4 ms
    g.V().order().by('name'), 31,846 vertices 622.5 ms 150.3 ms 612.5 ms 894.8 ms 613.7 ms 299.4 ms

    The traversals which this change leaves as they were took as long as on master, from 5.4% less to 2.6% more on any of the backends: g.V().hasLabel('person').order().by('name').limit(10), as no index restricted to person holds name; has('tag', 'rare') and has('tag', 'none') before order().by('name').limit(10) of the vertices and order().by('weight').limit(10) of the edges; order().by('name').by('tag'); orders by the keys of two indexes and by description; and the traversals which an index answered before, has('kind', 'k7') of a composite index and has('name', gt(…)) of mixed. An order by keys which no mixed index holds, tag and uid, which reads every vertex with either jar, moved by −9.6% to +8.1% between runs. At 4 threads, the first seven traversals of the table took 99% to 100% less time on every backend; the deep range 89% less on Lucene, 67% less on Elasticsearch and 71% less on Solr; the whole order 84% less on Lucene, 54% less on Solr and 5.7% more on Elasticsearch; and the others moved by −3.3% to +4.6%, but for the order by tag and uid, by up to 8.1%.

    The whole order is the one which takes longer, and only on Elasticsearch, which returns a result without a limit in pages of index.search.max-result-set-size, 50 by default: some 640 requests here. In a run of that traversal alone, it took 938 and 907 ms in two passes with pages of 50, 261 and 259 ms with pages of 1,000, and 201 and 201 ms with pages of 10,000, where master's scan took 615 and 606 ms. The scans here read an inmemory backend; one of a storage backend over a network costs more for each vertex, which the traversals that read only the first elements of the index don't pay.

    Solr read a result larger than a page at growing offsets, in pages of max-result-set-size, so that the work of an order without a limit, or with a limit beyond a page, grew with the square of its elements: with master's janusgraph-solr, this change took 2,944 ms for range(20000, 20010) and 5,920 ms for the whole order, where master's scan took 607 and 622 ms. Read Solr results larger than a page in growing pages #5127 reads such a result in pages which grow up to index.search.solr.max-page-size; with it on both sides, this change took 193 and 299 ms, as the table shows. So Read Solr results larger than a page in growing pages #5127 should be merged before this change.

    An earlier version of this change took the second choice also where JanusGraph checks some of the conditions in memory, as it does for a has(key) next to them: it reads the index in growing batches and checks each element it returns. Measured in the same way against master 3148803d4, it answered g.V().hasLabel('person').order().by('name').limit(10) with the index of every vertex in about 1.1 ms rather than 571 to 582 ms on Lucene and Elasticsearch, and took 60% less time on Lucene and 26% less on Elasticsearch for has('tag', 'rare') before the order of the vertices, and 33% less on Lucene for has('tag', 'none'). But it took 92% longer for has('tag', 'none') on Elasticsearch, where the batches beyond 10,000 hits come in pages, and longer for the edges, each of which an index hit looks up with a query of its own where a scan reads a vertex's edges at once: for has('tag', 'none'), 78% longer on Lucene and 345% longer on Elasticsearch, and for has('tag', 'rare'), 74% longer on Elasticsearch; order().by('name').by('tag'), which the index can't sort, took 11% longer on Elasticsearch. So this change takes the second choice only where the index answers every condition, and leaves the others as they were.

  • Visibility: these traversals now see what a has(key) sees, as the changelog says, where the scan read what the storage backend holds. An element committed moments before may be missing until the index shows it: Elasticsearch, with bulk-refresh at its default of false, once it refreshes; Solr, with wait-searcher at its default of false, once a commit opens a new searcher, which the shipped solrconfig.xml leaves to solr.autoSoftCommit.maxTime (its hard commits every 15 seconds don't open one). The other way round, an element whose order key was removed moments before may still come back, and one whose value changed may come in the order of its old value: QueryProcessor checks the results of a fitted query against its conditions in memory only for the transaction's own changes (getFilterIterator(…, hasDeletions, !subquery.isFitted())). A vertex removed moments before may come back too, as for a has(key): the index's ids become vertices by getInternalVertex, which by default doesn't read the vertex to check that it exists. A Java check bears both out: where a Lucene index still held a vertex which another graph instance on the same BerkeleyJE storage had removed, and the old name of a vertex which it had renamed from c to 0, g.V().order().by('name') returned the removed vertex, without a uid or a name, first, and the renamed one last, as g.V().has('name').order().by('name') does on master; master's full scan returned the renamed vertex first and not the removed one. So may an element whose index write or delete failed.

  • A key in two mixed indexes, as STRING in one and as TEXT in the other, neither restricted to a label: the candidates leave out the TEXT one, so g.V().order().by('name') reads the STRING one every time, where a check of the strategy's choice afterwards would read every element now and then, as Candidates above explains. Two indexes which both hold the key in a way which the backends sort by, as STRING and TEXTSTRING, are still taken by chance; each returns the same elements in the same order, but for the order of ties.

  • The filter takes each backend's answer, through IndexSelectionUtil.indexCoversOrder and Sort in memory the orders by keys which the index backend can't sort #5121's IndexSerializer.supportsOrdering: an order by a UUID reads the index on Elasticsearch and Solr, which sort UUIDs by their string forms, as JanusGraph orders them, and one by a STRING key with a string-analyzer reads it on Lucene and Solr, which sort such a key by its whole strings. It adds only a rule for custom parameters, which supportsOrdering doesn't look at: an index which holds an order key with custom parameters is left out on every backend, though only Elasticsearch takes them into its mapping. Such an order reads every element, as before, which costs nothing against master.

  • Index providers of other projects which keep IndexProvider.supportsOrdering's default of true are taken to sort by every key: such an order now reads their index, also by a key which they can't sort by, as one of TEXT mapping, where it read every element. They should implement supportsOrdering, as Sort in memory the orders by keys which the index backend can't sort #5121's changelog asks, and the changelog of this change says so too.

  • Elements which tie on the order keys may come in another order than before, the index's, so that a limit may take others of them. So may elements whose Instant values differ by less than a millisecond: Elasticsearch and Lucene keep instants by the millisecond, and Solr takes no finer one, where JanusGraph compares them whole. Leaving Instant keys out of the second choice would keep the order of such elements exact, at the cost of every order by a timestamp; the changelog says it instead.

  • Unchanged, and a bug of its own: where an index answers a traversal's conditions, Sort in memory the orders by keys which the index backend can't sort #5121 gives it the order only by the keys which its backend sorts by, but still by a key which it holds with custom parameters, and by one whose field isn't ENABLED, as IndexSelectionUtil.indexCoversOrder checks neither. With kind and tag in one Elasticsearch index, tag with doc_values false, g.V().has('kind', 'k').order().by('tag') fails with Could not call index; and with rank added to an index of kind and not yet reindexed, g.V().has('kind', 'k').order().by('rank') comes in the order of the index, which lacks the rank of every element which it held before. The second choice leaves both out, by its rule for custom parameters and as it covers the presence of a key only in an ENABLED field.

🤖 Generated with Claude Code

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Cross-backend ordering, custom index selection, and result-visibility changes warrant final human validation despite extensive regression coverage.

No open issues 🎉

What changed in this PR

Addresses #5124 by allowing ordered traversals to use a single mixed index that covers all order keys and conditions, avoiding full scans when eligible.

Changes:

  • Adds fallback index selection using order-key presence conditions, with safeguards for unsupported sorting and custom strategy choices.
  • Adds regression coverage for index selection, ordering, transaction changes, aggregations, and query.force-index.
  • Documents eligibility rules, performance tradeoffs, and changes in index-backed result visibility.
File Description
janusgraph-es/​src/​test/​java/​org/​janusgraph/​diskstorage/​es/​ElasticsearchJanusGraphIndexTest.java Tests scan fallback for string analyzers and custom mappings.
janusgraph-core/​src/​main/​java/​org/​janusgraph/​graphdb/​query/​graph/​GraphCentricQueryBuilder.java Adds guarded fallback selection of a fully covering mixed index.
janusgraph-backend-testutils/​src/​main/​java/​org/​janusgraph/​graphdb/​JanusGraphIndexTest.java Adds shared regression tests and updates index-use expectations.
janusgraph-backend-testutils/​src/​main/​java/​org/​janusgraph/​graphdb/​CandidateIgnoringIndexSelectionStrategy.java Adds a test strategy that selects outside supplied candidates.
docs/​schema/​index-management/​index-performance.md Explains when ordered traversals use mixed indexes or scans.
docs/​changelog.md Records behavior, performance, and visibility changes.

Review effort: Balanced

Fixes JanusGraph#5124

Since JanusGraph#5108, a traversal's order().by(key) requires a value of the key,
so g.V().order().by("name").limit(10) returns what
g.V().has("name").order().by("name").limit(10) returns. The second reads
the mixed index which holds name with an exists query, sorted by the
index, and stops after the first hits. The first has no condition which
an index answers, so it read every vertex and sorted them in memory,
which fails with a QueryException from a million vertices on, and which
query.force-index refused as a full scan. So did
g.V().hasLabel("person").order().by("name").limit(10) with an index of
the persons, and an order of edges by a key of an edge mixed index. The
presence of the order keys joined the query's condition only after the
index selection strategy had chosen the indexes for the other
conditions, so that it would not add a mixed index next to one which
answers them, which a joint query reads whole.

Where the strategy chooses no index for the query's own conditions, it
now chooses again for those conditions together with the presence of a
value of each order key, among the mixed indexes of the result type
which may answer them, as its own candidates, and which sort the
elements by the query's order: which hold every order key, which their
backend sorts by as JanusGraph orders its values, a key of several
values included (IndexSelectionUtil.indexCoversOrder, which asks each
backend since JanusGraph#5121), and none of them with custom parameters, which
Elasticsearch takes into its mapping, so that they may keep it from
sorting by the key. The brute-force strategy, which the default one
takes up to query.index-select-threshold candidates, weighs an index
which holds a key as a text, which no backend sorts by, as one which
holds it as a string: left among the candidates, such an index would be
taken in place of one which holds the key as a string, by chance, where
both answer the query alike. The approximate strategy prefers the one
which sorts, by indexCoversOrder.

The query takes that choice where it is a single index which covers
every condition: a mixed index which holds every order key and answers
the query whole, as it answers a has(key). It takes it only where the
index is one of the candidates, as nothing keeps a strategy from taking
another one. The query is then fitted, and sorted where the index sorts
by the query's order, as it does with JanusGraph's strategies
(sortedOnlyWhereTheIndexSorts checks it), so that a limit reads only the
first hits, and a count() or an aggregation of a key of the index right
after the order comes from the index. The strategies decide as for a
has(key) whether a mixed index covers such a condition, by the status of
the key's field and IndexSerializer.supportsExistsQuery, and take an
index restricted to a label only for a query of that label, whose
condition the index then covers too.

Any other query reads every element as before. One whose index would
leave a condition to be checked in memory would read the index in
growing batches and look each element up, and a joint query of several
indexes reads all but the first whole: every element with a value of
their keys. An or() alone still runs each of its branches as a query of
its own where no index covers it in the first choice, as none covers it
in the second either. A query of JanusGraph's API, which keeps the
elements without the key, is unaffected.

Signed-off-by: Oleksandr Porunov <alexandr.porunov@gmail.com>
Co-authored-by: Oleksandr Porunov <alexandr.porunov@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
@porunov
porunov force-pushed the order-by-key-reads-its-mixed-index branch from 73ac4a0 to fbce7da Compare October 23, 2026 21:02
@porunov
porunov requested a balanced review from Copilot October 23, 2026 21:05

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The cross-backend planner change requires human confirmation of backend CI results and merge sequencing with Solr paging prerequisite #5127.

No open issues 🎉

Review effort: Balanced

@porunov
porunov marked this pull request as ready for review October 24, 2026 00:05
@porunov porunov added this to the 1.2.0 milestone Oct 24, 2026
@porunov
porunov merged commit 0f578b3 into JanusGraph:master Oct 24, 2026
216 of 324 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

An ordered traversal which a mixed index of its order key could answer reads every element

2 participants