具有多值字段的弹性搜索查询构建器

Elastic search query builder with multi value fields

我有多个值字段,比如字段 A 可以有数据,比如 ("x", "y" ),("x"),("y", "z") 和 ("x","z ”)。假设客户端想要查询 ElasticSearch 以获取 A =“x”的 A 的那些值,在这种情况下我只想 return 1 条记录,其中 A = [“x”],但 TermQueryBuilder 会 return无论它在哪里找到“x”,即 ["x", "y" ],["x"], ["x","z"]

 final BoolQueryBuilder termQueryBuilder = new BoolQueryBuilder();
        termQueryBuilder.must(new TermQueryBuilder(filter.getDimension(), filter.getValue()));
        return termQueryBuilder; 

请告诉我如何确保它 return 只有 1 条记录,只有完全匹配的数据应该 returned

您可以使用 script query 以及术语查询,以根据提供的脚本过滤文档。

{
  "query": {
    "bool": {
      "filter": {
        "script": {
          "script": {
            "source": "doc['A.keyword'].length == 1",
            "lang": "painless"
          }
        }
      },
      "must": {
        "term": {
          "A": "x"
        }
      }
    }
  }
}

搜索结果将是

"hits": [
      {
        "_index": "70343831",
        "_type": "_doc",
        "_id": "2",
        "_score": 0.15965708,
        "_source": {
          "A": [
            "x"
          ]
        }
      }
    ]