From a4e4235d93a12cebe397f5225ebc2de1a174dda8 Mon Sep 17 00:00:00 2001 From: Shay Banon Date: Sat, 31 Dec 2011 16:24:27 +0200 Subject: [PATCH] move sort optimization when sorting by _score to sort parse element from the query phase execution --- .../elasticsearch/search/query/QueryPhase.java | 16 +--------------- .../search/sort/SortParseElement.java | 16 +++++++++++++++- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/src/main/java/org/elasticsearch/search/query/QueryPhase.java b/src/main/java/org/elasticsearch/search/query/QueryPhase.java index 21dffcb6001..a305d73f2e2 100644 --- a/src/main/java/org/elasticsearch/search/query/QueryPhase.java +++ b/src/main/java/org/elasticsearch/search/query/QueryPhase.java @@ -176,20 +176,6 @@ public class QueryPhase implements SearchPhase { // if 0 was asked, change it to 1 since 0 is not allowed numDocs = 1; } - boolean sort = false; - // try and optimize for a case where the sorting is based on score, this is how we work by default! - if (searchContext.sort() != null) { - if (searchContext.sort().getSort().length > 1) { - sort = true; - } else { - SortField sortField = searchContext.sort().getSort()[0]; - if (sortField.getType() == SortField.SCORE && !sortField.getReverse()) { - sort = false; - } else { - sort = true; - } - } - } if (searchContext.searchType() == SearchType.COUNT) { CountCollector countCollector = new CountCollector(); @@ -207,7 +193,7 @@ public class QueryPhase implements SearchPhase { // all is well } topDocs = scanCollector.topDocs(); - } else if (sort) { + } else if (searchContext.sort() != null) { topDocs = searchContext.searcher().search(query, null, numDocs, searchContext.sort()); } else { topDocs = searchContext.searcher().search(query, numDocs); diff --git a/src/main/java/org/elasticsearch/search/sort/SortParseElement.java b/src/main/java/org/elasticsearch/search/sort/SortParseElement.java index bbf2a51b9df..eb72e40c023 100644 --- a/src/main/java/org/elasticsearch/search/sort/SortParseElement.java +++ b/src/main/java/org/elasticsearch/search/sort/SortParseElement.java @@ -76,7 +76,21 @@ public class SortParseElement implements SearchParseElement { addCompoundSortField(parser, context, sortFields); } if (!sortFields.isEmpty()) { - context.sort(new Sort(sortFields.toArray(new SortField[sortFields.size()]))); + // optimize if we just sort on score non reversed, we don't really need sorting + boolean sort; + if (sortFields.size() > 1) { + sort = true; + } else { + SortField sortField = sortFields.get(0); + if (sortField.getType() == SortField.SCORE && !sortField.getReverse()) { + sort = false; + } else { + sort = true; + } + } + if (sort) { + context.sort(new Sort(sortFields.toArray(new SortField[sortFields.size()]))); + } } }