Elasticsearch 匹配给定数组中的所有标签

Wil*_*aul 5 search json node.js elasticsearch

目前正在使用 elasticsearch 开发标签搜索应用程序,我为索引中的每个文档提供了一个标签数组,以下是文档外观的示例:

_source: {
  title: "Keep in touch scheme",
  intro: "<p>hello this is a test</p> ",
  full: " <p>again this is a test mate</p>",
  media: "",
  link: "/training/keep-in-touch",
  tags: [
    "employee",
    "training"
  ]
}
Run Code Online (Sandbox Code Playgroud)

我希望能够进行搜索并且只返回带有所有指定标签的文档。

使用上面的例子,如果我搜索带有标签的文档 ["employee", "training"]则将返回上述结果。

相反,如果我用标签搜索 ["employee", "other"],则不会返回任何内容;搜索查询中的所有标签都必须匹配。

目前我正在做:

query: {
  bool: {
    must: [
      { match: { tags: ["employee","training"] }}
     ]
   }
 }
Run Code Online (Sandbox Code Playgroud)

但我只是收到返回的异常,例如

IllegalStateException[Can't get text on a START_ARRAY at 1:128];
Run Code Online (Sandbox Code Playgroud)

我还尝试连接数组并使用逗号分隔的字符串,但是这似乎与第一个标签匹配的任何内容相匹配。

关于如何解决这个问题的任何建议?干杯

Vla*_*pak 1

选项 1:下一个示例应该可以工作(v2.3.2):

curl -XPOST 'localhost:9200/yourIndex/yourType/_search?pretty' -d '{
  "query": {
    "bool": {
      "must": [
        { "term": { "tags": "employee" } } ,
        { "term": { "tags": "training" } }
      ]
    }
  }
}'
Run Code Online (Sandbox Code Playgroud)

选项 2:您也可以尝试:

curl -XPOST 'localhost:9200/yourIndex/yourType/_search?pretty' -d '{
  "query": {
    "filtered": {
      "query": {"match_all": {}},
      "filter": {
        "terms": {
          "tags": ["employee", "training"]
        }
      }
    }
  }
}'
Run Code Online (Sandbox Code Playgroud)

但如果没有"minimum_should_match": 1它,小垃圾箱就不准确。我也发现了"execution": "and",但它的工作也不准确。

选项 3:你也可以尝试一下,query_string它工作得很好,但看起来有点复杂:

curl -XPOST 'localhost:9200/yourIndex/yourType/_search?pretty' -d '{
"query" : {
    "query_string": {
      "query": "(tags:employee AND tags:training)"
    }
  }
}'
Run Code Online (Sandbox Code Playgroud)

也许它会对你有帮助......