diff --git a/presto-elasticsearch/src/main/java/com/facebook/presto/elasticsearch/ElasticsearchClient.java b/presto-elasticsearch/src/main/java/com/facebook/presto/elasticsearch/ElasticsearchClient.java index 7879569be8d8..dd2210964b04 100644 --- a/presto-elasticsearch/src/main/java/com/facebook/presto/elasticsearch/ElasticsearchClient.java +++ b/presto-elasticsearch/src/main/java/com/facebook/presto/elasticsearch/ElasticsearchClient.java @@ -483,12 +483,14 @@ else if (value.has("properties")) { return new IndexMetadata.ObjectType(result.build()); } - public SearchResponse beginSearch(String index, int shard, QueryBuilder query, Optional> fields, List documentFields) + public SearchResponse beginSearch(String index, int shard, QueryBuilder query, Optional> fields, List documentFields, Optional sort) { SearchSourceBuilder sourceBuilder = SearchSourceBuilder.searchSource() .query(query) .size(scrollSize); + sort.ifPresent(sourceBuilder::sort); + fields.ifPresent(values -> { if (values.isEmpty()) { sourceBuilder.fetchSource(false); diff --git a/presto-elasticsearch/src/main/java/com/facebook/presto/elasticsearch/ElasticsearchPageSource.java b/presto-elasticsearch/src/main/java/com/facebook/presto/elasticsearch/ElasticsearchPageSource.java index 51e2e950cd13..47c3d748f251 100644 --- a/presto-elasticsearch/src/main/java/com/facebook/presto/elasticsearch/ElasticsearchPageSource.java +++ b/presto-elasticsearch/src/main/java/com/facebook/presto/elasticsearch/ElasticsearchPageSource.java @@ -122,13 +122,23 @@ public ElasticsearchPageSource( .filter(name -> !BuiltinColumns.NAMES.contains(name)) .collect(toList()); + // sorting by _doc (index order) get special treatment in Elasticsearch and is more efficient + Optional sort = Optional.of("_doc"); + + if (table.getQuery().isPresent()) { + // However, if we're using a custom Elasticsearch query, use default sorting. + // Documents will be scored and returned based on relevance + sort = Optional.empty(); + } + long start = System.nanoTime(); SearchResponse searchResponse = client.beginSearch( split.getIndex(), split.getShard(), buildSearchQuery(session, split.getTupleDomain().transform(ElasticsearchColumnHandle.class::cast), table.getQuery()), needAllFields ? Optional.empty() : Optional.of(requiredFields), - documentFields); + documentFields, + sort); readTimeNanos += System.nanoTime() - start; this.iterator = new SearchHitIterator(client, () -> searchResponse); }