如何在Elasticsearch中构造一个带有过滤器数组的QueryBuilder?

时间:2019-06-04 22:33:00

标签: java elasticsearch

我希望将以下查询转换为QueryBuilder类型的对象:

{
  "query": {
    "bool": {
      "filter": [
        { "term": { "field1": "val1"}},
        { "range": {
          "field2": {"lte": val}}

        },
        {"nested": {
          "path": "field3",
          "score_mode": "none",
          "query": {
            "bool": {
              "filter": [
                {"term": {"field3.key": "foo"}},
                {"term": {"field3.val": "bar"}}
              ]
            }
          }
        }}
      ]
    }
  }
} 

请注意,两个实例中的filter键实际上都承载着一系列查询。

到目前为止,我的Google-fu让我失败了。我该如何构建该对象?它像创建一个BoolQueryBuilder对象并对其调用3次filter方法那样简单吗?

1 个答案:

答案 0 :(得分:1)

例如,您从内部搜索对象开始向外创建对象:

var innerSearch = new BoolQueryBuilder();
innerSearch.must(QueryBuilders.termsQuery("field3.key", "foo" ));
innerSearch.must(QueryBuilders.termsQuery("field3. val", "bar" ));

现在您将内部搜索添加到外部搜索,在您的情况下,内部搜索是嵌套对象

NestedQueryBuilder nestedQueryBuilder = QueryBuilders.nestedQuery("field3",innerSearch, ScoreMode.None);


var outerSearch = new BoolQueryBuilder();
outerSearch.filter(nestedQueryBuilder)