【发布时间】:2021-11-11 04:38:11
【问题描述】:
我需要对每个文档的某些字段进行一些计算,然后将其作为响应的一部分返回 我写了这个
TermsAggregationBuilder subAggregation = AggregationBuilders
.terms("price")
.script(new Script(ScriptType.INLINE, "painless",
" int total = 0;\n" +
" for (int i = 0; i < 5; ++i) {\n" +
" total += doc['age'].value;\n" +
" }\n" +
" return total ;\n"
, Collections.emptyMap()));
NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder()
.withQuery(matchAllQuery())
.addAggregation(subAggregation)
.build();
SearchHits<Stories>
searchHits = elasticsearchOperations.search(nativeSearchQuery, Stories.class
, IndexCoordinates.of("long_stories"));
这会返回这个
{
"totalHits": 1,
"totalHitsRelation": "EQUAL_TO",
"maxScore": 1,
"scrollId": null,
"searchHits": [
{
"id": "44",
"score": 1,
"sortValues": [],
"content": {
"id": "44",
"innerId": 5,
"age": 44,
"salary": 433,
"mark": 10,
"state": "state",
"stores": [
{
"storiesId": "44",
"innerId": 1
},
{
"storiesId": "44b",
"innerId": 2
},
{
"storiesId": "44c",
"innerId": 3
}
],
"esh": null
},
"highlightFields": {}
}
],
"aggregations": {
"asMap": {
"price": {
"name": "price",
"metadata": null,
"buckets": [
{
"aggregations": {
"asMap": {},
"fragment": true
},
"keyAsString": "220",
"docCount": 1,
"docCountError": 0,
"key": "220",
"keyAsNumber": 220,
"fragment": true
}
],
"type": "sterms",
"docCountError": 0,
"sumOfOtherDocCounts": 0,
"fragment": true
}
},
"fragment": true
},
"empty": false
}
这个响应给出了单独的计算,我需要它与上面的部分,如果我现在有一些另一个文档会给出相同的答案,那么如果键是 220,那么响应将打印 220 和文档计数 2 我需要它分别并在上述响应中 像 doc1 220 doc2 220 和上述响应中的实际数据
【问题讨论】:
-
术语聚合用作“分组依据”。因此,它将只有唯一的密钥和包含在这些密钥下的文档。如果您在每个文档的基础上需要它,请在查询中使用脚本字段而不是聚合b
-
嗨,谢谢,我喜欢这个 ScriptField 并添加到查询 withScriptedField 但现在它返回脚本字段,如年龄和其他 null
-
您需要专门提供 "_source": ["*"],
-
它不是脚本的一部分。它是搜索请求的一部分。我不知道java框架。它应该类似于 nativeSearchQuery.addSourceFilter(new FetchSourceFilter(includeSources)) 或 nativeSearchQuery.fetchSource(true)。 includeSources 是字符串字段名列表
-
stackoverflow.com/users/9279354/jaspreet-chahal。非常感谢它解决了我所有的问题非常感谢