一、需求
操作多层嵌套的Json数据,修改key值或删除key,然后更新原始Json数据
二、期望效果
删除原始Json中query-->bool-->should-->match_phrase-->recallChar2-->zero_terms_query字段(key)
,然后更新原始Json。
Json数据格式如下:
原始Json
{
"query": {
"bool": {
"filter": [
{
"term": {
"label.keyword": {
"boost": 1.0,
"value": "字符串"
}
}
}
],
"adjust_pure_negative": true,
"should": [
{
"match": {
"recallChar2": {
"auto_generate_synonyms_phrase_query": true,
"query": "测试",
"zero_terms_query": "NONE",
"fuzzy_transpositions": true,
"boost": 1.0,
"prefix_length": 0,
"operator": "OR",
"lenient": false,
"max_expansions": 50
}
}
},
{
"match_phrase": {
"recallChar2": {
"query": "测试",
"zero_terms_query": "NONE",
"boost": 1.0,
"slop": 0
}
}
}
],
"boost": 1.0
}
}
}
新Json
{
"query": {
"bool": {
"filter": [
{
"term": {
"label.keyword": {
"boost": 1.0,
"value": "字符串"
}
}
}
],
"adjust_pure_negative": true,
"should": [
{
"match": {
"recallChar2": {
"auto_generate_synonyms_phrase_query": true,
"query": "测试",
"zero_terms_query": "NONE",
"fuzzy_transpositions": true,
"boost": 1.0,
"prefix_length": 0,
"operator": "OR",
"lenient": false,
"max_expansions": 50
}
}
},
{
"match_phrase": {
"recallChar2": {
"query": "测试",
"boost": 1.0,
"slop": 0
}
}
}
],
"boost": 1.0
}
}
}
三、实现
//入参esSearchRequestParam:原始Json 返参:新Json
private JSONObject updateEsRequestParam(JSONObject esSearchRequestParam) {
Object bool = JSONObject.parseObject(esSearchRequestParam.get("query").toString()).get("bool");
Object should = JSONObject.parseObject(bool.toString()).get("should");
JSONArray shouldArray = JSONObject.parseArray(should.toString());
for (int i = 0; i < shouldArray.size(); i++) {
JSONObject jsonObject = shouldArray.getJSONObject(i);
if (jsonObject.containsKey("match_phrase")){
Object matchPhrase = jsonObject.get("match_phrase");
Object recallChar2 = JSONObject.parseObject(matchPhrase.toString()).get("recallChar2");
JSONObject recallChar2New = JSONObject.parseObject(recallChar2.toString());
// jsonObject1.fluentPut("zero_terms_query","测试");
recallChar2New.remove("zero_terms_query");
Object matchPhraseNew = JSONObject.parseObject(matchPhrase.toString()).fluentPut("recallChar2", recallChar2New);
jsonObject.fluentPut("match_phrase", matchPhraseNew);
}
}
JSONObject boolNew = JSONObject.parseObject(bool.toString()).fluentPut("should", shouldArray);
JSONObject queryNew = JSONObject.parseObject(esSearchRequestParam.get("query").toString()).fluentPut("bool", boolNew);
return esSearchRequestParam.fluentPut("query", queryNew);
}
四、总结
遇到这类问题先分析Json的数据格式