我试图在“必须”子句中为我的ES查询添加前缀条件。
我当前的查询看起来像这样:
body = {
"query": {
"bool": {
"must":
{ "term": { "article_lang": 0 }}
,
"filter": {
"range": {
"created_time": {
"gte": "now-3h"
}
}
}
}
},
"aggs": {
"articles": {
"terms": {
"field": "article_id.keyword",
"order": {
"score": "desc"
},
"size": 1000
},
"aggs": {
"score": {
"sum": {
"field": "score"
}
}
}
}
}
}
我需要在查询中添加一个强制性条件,以过滤ID以“article-”开头的文章。
因此,到目前为止,我已经尝试过了:
{
"query": {
"bool": {
"should": [
{ "term": { "article_lang": 0 }},
{ "prefix": { "article_id": {"value": "article-"} }}
],
"filter": {
"range": {
"created_time": {
"gte": "now-3h"
}
}
}
}
},
"aggs": {
"articles": {
"terms": {
"field": "article_id.keyword",
"order": {
"score": "desc"
},
"size": 1000
},
"aggs": {
"score": {
"sum": {
"field": "score"
}
}
}
}
}
}
我对ES还是相当陌生,从在线文档中可以得知,“应该”用于“或”条件,“必须”用于“与”条件。这返回了一些数据,但根据条件,它将由article_lang = 0或以article-开头的文章组成。当我使用“必须”时,它不返回任何内容。
我敢肯定,有ID开头为前缀的文章,因为当前,我们正在迭代此结果以过滤掉此类文章。我在这里想念什么?
最佳答案
在prefix
查询中,您需要使用article_id.keyword
字段,而不是article_id
。另外,您应该更喜欢filter
而不是must
,因为您只是在进行是/否匹配(又名过滤器)
{
"query": {
"bool": {
"filter": [ <-- change this
{
"term": {
"article_lang": 0
}
},
{
"prefix": {
"article_id.keyword": { <-- and this
"value": "article-"
}
}
}
],
"filter": {
"range": {
"created_time": {
"gte": "now-3h"
}
}
}
}
},
"aggs": {
"articles": {
"terms": {
"field": "article_id.keyword",
"order": {
"score": "desc"
},
"size": 1000
},
"aggs": {
"score": {
"sum": {
"field": "score"
}
}
}
}
}
}
关于elasticsearch - ElasticSearch查询带有聚合前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59171681/