[英]How to count Elastic Search documents based on multiple field values with the Java API?
I am attempting to count the number of documents of a specific type based on the value of 2 of the documents fields. 我正在尝试根据document字段的值2来计算特定类型的文档数。
So far I can count the number of documents using: 到目前为止,我可以使用以下方法计算文档数:
SearchResponse response = elasticClient.getClient().prepareSearch(Properties.get().getSearch().getAliasName())
.setTypes(type)
.setSize(0) // Don't return any documents, we don't need them.
.get();
SearchHits hits = response.getHits();
return (int) hits.getTotalHits();
Which returns the correct number of total documents. 返回正确的文档总数。
I can also search for a specific document using: 我还可以使用以下方法搜索特定文档:
searchResponse = elasticClient.getClient()
.prepareSearch(index)
.setSearchType(SearchType.QUERY_THEN_FETCH)
.setQuery(QueryBuilders.prefixQuery(field_name, field_value))
.setFetchSource(true)
.setSize(10000)
.setTypes(type)
.addSort(builder.order(SortOrder.DESC))
.get();
This also returns documents. 这也将返回文档。
I have attempted to count based on 2 field values using: 我尝试使用以下方法基于2个字段值进行计数:
BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
queryBuilder.must(QueryBuilders.prefixQuery(field_1, value_1));
queryBuilder.must(QueryBuilders.prefixQuery(field_2, value_2));
SearchRequestBuilder searchBuilder = elasticClient.getClient().prepareSearch(index)
.setQuery(queryBuilder)
.setTypes(type)
.setSize(0);
But this always returns 0. 但这始终返回0。
How do I correctly count documents based on 2 field values using the Java API? 如何使用Java API根据2个字段值正确计数文档?
From inspecting the query, you are not passing both values together. 通过检查查询,您不会将两个值一起传递。 You are first passing the query for field_1
and later overwriting it with the query for field_2
. 您首先要传递对field_1
的查询,然后用对field_2
的查询覆盖它。 So the variable queryBuilder
only has the query: QueryBuilders.prefixQuery(field_2, value_2)
by the time you pass it to the client. 因此,在将变量传递给客户端QueryBuilders.prefixQuery(field_2, value_2)
变量queryBuilder
仅具有查询: QueryBuilders.prefixQuery(field_2, value_2)
。
In elasticsearch query DSL, the must
object is an array of queries that behave similar to an AND
in a SQL where clause. 在Elasticsearch查询DSL中, must
对象是一系列查询,其行为类似于SQL where子句中的AND
。 So all the queries in the must
list need to match. 因此must
列表中的所有查询都must
匹配。 To include both queries in the must
do the following: 要将两个查询都包括在内, must
执行以下操作:
BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
queryBuilder.must().add(QueryBuilders.prefixQuery(field_1, value_1));
queryBuilder.must().add(QueryBuilders.prefixQuery(field_2, value_2));
As for the count, size = 0
should do the trick. 至于计数, size = 0
应该可以解决问题。 What kind of elasticsearch client are you using? 您使用哪种弹性搜索客户端?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.