如何控制Elasticsearch Java QueryBuilder转为更简洁的JSON字符串?
解决Elasticsearch QueryBuilder转精简JSON字符串的问题
刚好碰到过类似的需求!默认的QueryBuilder.toString()会把所有默认参数(比如示例里的boost:1.0)都输出,导致JSON过于冗长。要得到只包含必要字段的精简版,你可以用Elasticsearch自带的XContentBuilder来手动序列化,跳过那些默认值。
核心解决方案代码
直接替换你原来的输出逻辑就行,注意处理一下异常:
import org.elasticsearch.index.query.QueryBuilder; import static org.elasticsearch.index.query.QueryBuilders.termQuery; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentBuilder; public class MyQueryPrinter { public static void main(String[] args) throws Exception { QueryBuilder myQuery = termQuery("brand", "gucci"); // 生成一行精简版JSON XContentBuilder builder = XContentFactory.jsonBuilder(); myQuery.toXContent(builder, XContentBuilder.ToXContent.EMPTY_PARAMS); System.out.println(builder.string()); /* 输出结果: {"term":{"brand":"gucci"}} */ } }
可选:格式化后的精简版
如果你想要可读性更好的格式化输出,但还是保留精简的字段,只需要给XContentBuilder加上prettyPrint():
XContentBuilder builder = XContentFactory.jsonBuilder().prettyPrint(); myQuery.toXContent(builder, XContentBuilder.ToXContent.EMPTY_PARAMS); System.out.println(builder.string()); /* 输出结果: { "term" : { "brand" : "gucci" } } */
原理说明
默认的toString()方法其实是调用了包含默认参数的序列化逻辑,会把所有可选配置的默认值都写入JSON。而toXContent配合EMPTY_PARAMS参数时,只会序列化你实际设置过的字段,那些有默认值的参数会被自动忽略,这样就得到了最紧凑的查询JSON。
内容的提问来源于stack exchange,提问作者selotape
相关产品推荐
相关产品推荐

