Elasticsearch 过滤多个术语,仅匹配结果,而不是其中任何一个

wal*_*oar 1 elasticsearch

如何通过所有多术语搜索仅获得过滤后的匹配结果。我有这个示例表,其中 titleid 是映射 int 字段,personid 是关键字:

titleid:1,personid:a
titleid:3,personid:a

titleid:1,personid:b
titleid:2,personid:b

titleid:1,personid:c
titleid:5,personid:c
Run Code Online (Sandbox Code Playgroud)

预期结果是:

titleid:1
Run Code Online (Sandbox Code Playgroud)

使用如下示例查询:

{query:
    {bool:
    {filter:
            {must:[
                    {terms : {fields: {personid:[a,b,c]}}
                 ]
            }}}}
Run Code Online (Sandbox Code Playgroud)

我有以下结果:

titleid: 1,2,3,5
Run Code Online (Sandbox Code Playgroud)

也许这会有所帮助,我在 sql 中进行了查询并得到了预期的结果。我所做的是要求查询给出与搜索参数数量匹配的 titleid 总和。这只是为了更自我解释,这个想法是使用elasticsearch。

select titleid
from (
   select count(titleid) as title_count, titleid 
   from table1 
   where personid in ('a','b','c')
   group by titleid
) as vw 
where title_count = 3
Run Code Online (Sandbox Code Playgroud)

den*_*nov 6

如果您只想使用titleid == 1AND记录personid == 'a',则可以对这两个字段进行过滤。仅布尔查询使用mustshouldmost_not。使用过滤器,因为根据定义它是过滤(例如,删除)must

"query": {
  "bool": {
    "filter": [
      {
        "term": {
          "titleId": { "value": 1 }
        } 
      },
      {
        "term": {
          "personid": { "value": "a" }
        }
      }
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

更新::

现在你的问题看起来像是你想要过滤和聚合你的结果,然后聚合这些结果。有一些指标存储桶聚合

使用存储桶选择器聚合 (这尚未经过测试,但如果不正确,应该非常接近)

{
    "aggs" : {
        "title_id" : {
            "filter" : { "terms": { "personid": ["a","b","c"] } },
            "aggs" : {
                "id_count" : { "count" : { "field" : "titleid" } }
            }
        },      
        aggs": {
            "count_filter": {
               "bucket_selector": {
                  "buckets_path": {
                     "the_doc_count": "_count"
                  },
                  "script": "the_doc_count == 3"
               }
            }
         }  
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,请注意,管道聚合对其他聚合产生的输出起作用,因此计算初始 doc_counts 所需完成的总体工作量将是相同的。由于需要对每个输入存储桶执行脚本部分,因此对于高基数字段(如成千上万个术语),操作可能会很慢。