ElasticSearch 查询为空的字符串

#ElasticSearch 最近在做功能的时候,碰到字符串为空的情况,使用exists没有办法过滤这种数据,再次记录一下,直接上代码

es中记录数据
"_index": "yt_evaluate_user",
"_type": "evaluate_user_label",
"_id": "AWl24HQmN4aMV7d2lfcZ",
"_score": 1,
"_source": {
	"place_id": "",
	"user_name": "test",
	"labeling_user_name": "",
	"label_type": 1,
	"create_date": "2019-03-13 19:46:55",
	"create_time": 1552477615752,
	"label_id": 11
}
es查询:
{
  "query": {
    "bool": {
      "must": [
        {
          "bool": {
            "must": {
              "exists": {
                "field": "labeling_user_name"
              }
            }
          }
        }
      ]
    }
  }
}
查询结果:
[]

此处可以发现,使用exists并没有过滤掉labeling_user_name为空的字符串的情况,查询官方文档,给出的结果是,空的字符串也是一种数据类型,而exists只能过滤掉为 null 的字段,其中不包括“”或“null”,如果要过滤空的字符串应使用filter

es查询:
{
  "query": {
    "bool": {
      "must": [
        {
          "bool": {
            "filter": {
              "term": {
                "labeling_user_name": ""
              }
            },
            "must": {
              "exists": {
                "field": "labeling_user_name"
              }
            }
          }
        }
      ]
    }
  }
}
查询结果:
"_index": "yt_evaluate_user",
"_type": "evaluate_user_label",
"_id": "AWm94tO3BuINW_Mx_HY7",
"_score": 2.1005976,
"_source": {
	"place_id": "",
	"user_name": "test",
	"labeling_user_name": "",
	"label_type": 1,
	"create_date": "2019-03-13 19:46:55",
	"create_time": 1552477615752,
	"label_id": 11
}

java代码如下:

BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
QueryBuilder labeling_user_name_qf = QueryBuilders.termQuery("labeling_user_name","");
QueryBuilder labeling_user_name_qb = QueryBuilders.existsQuery("labeling_user_name");
BoolQueryBuilder labeling_user_name_bqb = QueryBuilders.boolQuery().filter(labeling_user_name_qf).must(labeling_user_name_qb);
boolQueryBuilder.must(labeling_user_name_bqb);
SearchRequestBuilder requestBuilder = esClient.prepareSearch("yt_evaluate_user").setTypes("evaluate_user_label");
requestBuilder.setQuery(boolQueryBuilder);

你可能感兴趣的:(ElasticSearch笔记,ElasticSearch)