Elasticsearch 仅匹配过滤器

Elasticsearch match against filter only

我们有一个多租户索引,只需要针对单个租户的索引执行查询。基本上,对于所有匹配过滤器的文档,return 任何匹配以下查询的文档,但不包括仅匹配过滤器的文档。

例如,假设我们有一个文档列表,如下所示:

{ _id: 1, account_id: 1, name: "Foo" }
{ _id: 2, account_id: 2, name: "Bar" }
{ _id: 3, account_id: 2, name: "Foo" }

我认为这个查询会起作用,但它不起作用:

{
  "bool": {
    "filter": { "term": { "account_id": 2 } },
    "should": [
      { "match": { "name": "Foo" }
    ]
  }
}

它 return 两个文档匹配 account_id: 2:

{ _id: 3, account_id: 2, name: "Foo", score: 1.111 }
{ _id: 2, account_id: 2, name: "Bar", score: 0.0 }

我真正想要的只是 return 文档 _id: 3,基本上是 "Of all documents where account_id is equal to 2, return only the ones whose names match Foo".

如何使用 ES 6.2 完成此操作?需要注意的是 shouldmust 匹配条件的数量并不总是已知的,我真的想避免使用 minimum_should_match.

试试这个:只需将 should 替换为 must:

{
  "bool": {
    "filter": { "term": { "account_id": 2 } },
    "must": [
      { "match": { "name": "Foo" }
    ]
  }
}