为Elasticsearch客户端构建XContentBuilder JSON查询

时间:2019-03-28 10:36:19

标签: java elasticsearch groovy

基本上,我想使用<button>来获得此查询:

XContentBuilder

这是我的代码:

{"query":{
    "bool": {
        "must": [
            { "match": { "fields.title": "Star"}},
            { "match": { "fields.title": "Wars"}}
        ]
}}}

但是我得到了这个错误:

XContentBuilder query = XContentFactory.jsonBuilder()
def array = ["Star", "Wars"]
def field = "field.title"
query.startObject()
query.startObject("bool")
query.startArray("must")
array.each { value ->
    query.startObject("match")
    query.startObject()
    query.field(field, value)
    query.endObject()
    query.endObject()
}
query.endArray()
query.endObject()
query.endObject()
QueryBuilder finalQuery = QueryBuilders.wrapperQuery(query.string())

奇怪的是,当我删除Caused by: com.fasterxml.jackson.core.JsonGenerationException: Can not write a field name, expecting a value at com.fasterxml.jackson.core.JsonGenerator._reportError(JsonGenerator.java:1897) at com.fasterxml.jackson.core.json.UTF8JsonGenerator.writeFieldName(UTF8JsonGenerator.java:185) at org.elasticsearch.common.xcontent.json.JsonXContentGenerator.writeFieldName(JsonXContentGenerator.java:183) at org.elasticsearch.common.xcontent.XContentBuilder.field(XContentBuilder.java:246) at org.elasticsearch.common.xcontent.XContentBuilder.startObject(XContentBuilder.java:222) at gde.plugin.search.elasticsearch.ElasticSearchWrapper$_clientQuery_closure16$$ERM0UO5B.doCall(ElasticSearchWrapper.groovy:737) at gde.plugin.search.elasticsearch.ElasticSearchWrapper$$ERM0UO51.clientQuery(ElasticSearchWrapper.groovy:736) at gde.plugin.search.SearchService.test(SearchService.groovy:158) at gde.plugin.search.SearchController.test(SearchController.groovy:43) ... 36 common frames omitted 及其关联行query.startObject("match")时,没有更多错误,但这不是我想要的查询...

query.endObject()

1 个答案:

答案 0 :(得分:1)

您似乎需要额外的startObjectendObject通话。您需要这样做以便在每个match对象周围添加括号。代码应如下所示:

XContentBuilder query = XContentFactory.jsonBuilder()
def array = ["Star", "Wars"]
def field = "field.title"
query.startObject()
query.startObject("bool")
query.startArray("must")
array.each { value ->
    query.startObject()
    query.startObject("match")
    query.startObject()
    query.field(field, value)
    query.endObject()
    query.endObject()
    query.endObject()
}
query.endArray()
query.endObject()
query.endObject()
QueryBuilder finalQuery = QueryBuilders.wrapperQuery(query.string())