Jackson jsonGenerator生成Elasticsearch查询DSL

时间:2017-07-26 02:08:46

标签: elasticsearch jackson rest-client

我是Elasticserach和Jackson Json的新手。有一个简单的查询(按国家/地区搜索索引)我尝试使用JsonGenerator,

"{\n" +
    "    \"query\" : {\n" +
    "    \"match\": { \"exporting_country\":\"" + countryCode + "\"} \n" +
    "} \n"+
    "}"

JsonGenerator代码,

        JsonGenerator jGenerator = jfactory.createGenerator(outputStream);

        jGenerator.writeStartObject();
        jGenerator.writeFieldName("query");

        jGenerator.writeStartObject();

        jGenerator.writeFieldName("match");
        jGenerator.writeStringField("exporting_country", countryCode);

        jGenerator.writeEndObject();
        jGenerator.writeEndObject();
        jGenerator.close();

它抛出一个错误:

Can not write a field name, expecting a value

1 个答案:

答案 0 :(得分:0)

您错过了对writeStartObject的电话:

    JsonGenerator jGenerator = jfactory.createGenerator(outputStream);

    jGenerator.writeStartObject();
    jGenerator.writeFieldName("query");

    jGenerator.writeStartObject();

    jGenerator.writeFieldName("match");
    jGenerator.writeStartObject();             <--- add this
    jGenerator.writeStringField("exporting_country", countryCode);
    jGenerator.writeEndObject();               <--- and this

    jGenerator.writeEndObject();
    jGenerator.writeEndObject();
    jGenerator.close();