使用Java API动态构建Elastic Search查询

时间:2019-04-02 14:21:16

标签: java elasticsearch elasticsearch-java-api

想象一下以下文件:

[
  { "name" : "deepgreen", "colors" : [
    { "color" : "green" },
    { "color" : "black" }
    ]
  },
  { "name" : "lightblue", "colors" : [
    { "color" : "blue" },
    { "color" : "white" }
    ]
  },
  { "name" : "purple", "colors": [
    { "color" : "red" },
    { "color" : "blue" },
    { "color" : "white" }
    ]
  }
]

如果colors字段的类型为nested object,则此映射是正确的。我将执行以获取例如紫色的查询的是:

GET /colors/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "path": "colors",
            "query": {
              "match_phrase": {
                "colors.color": "blue"
              }
            }
          }
        },
        {
          "nested": {
            "path": "colors",
            "query": {
              "match_phrase": {
                "colors.color": "blue"
              }
            }
          }
        },
        {
          "nested": {
            "path": "colors",
            "query": {
              "match_phrase": {
                "colors.color": "blue"
              }
            }
          }
        },
        {
          "match_phrase": {
            "name": "purple"
          }
        }
      ]
    }
  }
}

如何使用ES Java API动态生成此查询?通过查看以下伪代码可以了解我正在尝试做的事情:

List<QueryBuilders> nestedQueryBuilders = new ArrayList<>();

colors.forEach(color -> {
    nestedQueryBuilders.add(new nestedQuery("colors",
            matchPhraseQuery("colors.color", color)),
            ScoreMode.Avg);
});

BoolQueryBuilder boolQuery = boolQuery()
    .must(matchPhraseQuery("name", "purple"))
    .must(nestedQueryBuilders);

SearchRequest request = new SearchRequest()
    .indices("colors")
    .source(new SearchSourceBuilder()
        .query(boolQuery));

client.search(request, RequestOptions.DEFAULT);

我还没有遇到一种将“子”查询动态添加到must-bool-query中的方法。

任何人都有这方面的经验,可以告诉我如何实现吗?

0 个答案:

没有答案