简体   繁体   English

Spring Elasticsearch-检索在字段中具有最大价值的文档

[英]Spring elasticsearch - retrieve document which has largest value in a field

I am looking for an elegant way to retrieve document that has largest value in a certain field of his. 我正在寻找一种优雅的方法来检索在他的特定领域具有最大价值的文档。 For example, I want to retrieve document that has largest timestamp. 例如,我要检索具有最大时间戳的文档。 I've tried using aggregations, but it I could not manage to get it working, it would only return a field. 我已经尝试过使用聚合,但是我无法使其正常运行,它只会返回一个字段。 I've also considered using sorting and the fetching the first element, but I find that a bit bruteforce. 我也考虑过使用排序和获取第一个元素,但是我发现这有点蛮力。 Such query would something like: 这样的查询将类似于:

  SearchQuery searchQuery = new NativeSearchQueryBuilder()
            .withPageable(new PageRequest(0, 1))
            .withSort(SortBuilders.fieldSort(FIELD_TIMESTAMP)
                    .order(SortOrder.DESC))
            .build();

Is there any better way of doing such a task? 有没有更好的方法来完成这样的任务?

You can use size() method of SearchResponse to get the document with highest response. 您可以使用SearchResponse的size()方法获取响应最高的文档。

For your query, it should be like this: 对于您的查询,应该是这样的:

FieldSortBuilder timestampSort = SortBuilders.fieldSort(FIELD_TIMESTAMP).order(SortOrder.DESC);

SearchResponse response = client.prepareSearch(index)
            .addSort(timestampSort)
            .setSize(1)
            .execute()
            .actionGet();

Above query will return only one document, ie: first document from your query response. 上面的查询将仅返回一个文档,即:查询响应中的第一个文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM