Elasticsearch 搜索不到数据问题(_mapping 设置)

时间:2023-03-09 14:20:44
Elasticsearch 搜索不到数据问题(_mapping 设置)

需求

由于 kibana3 中,不支持直接在请求的 url 中设置搜索的 type (是不是我不知道???)。

为了支持特定 type 的搜索,所以我设置了个下每个 panel 的查询语句,让它增加一个:

"query_string":
{"query": " _type:\"my_type\" "}

结果今天在查一个 bug 的时候,发现这样有一个坑,,,

问题

由于URL请求的路径并没不能指定 type ,所以每一次的搜索,依然会查询整个 index,只是在获取结果时候,再 query 了一次 "_type" 字段。

如果在同一个 index 下,存在不同 type 中,某个字段类型不一致的情况,那将可能导致搜索不到想要的结果。(因为不同的 type 有不同的 _mapping)

示例1:我在一个字段第一次存的时候,filed1 存为了 string 类型,而又新建了另一个 type,且 filed1 字段类型变为了 date,

后来在对这个字段进行时间 range 过滤操作的时候,发现总是匹配不到想要的结果,hits 总是空数组,

URL:http://localhost:9200/index/_search
{
"query": {
"filtered": {
"query": {
"bool": {
"should": [{
"query_string": {
"query": "_type:\"my_type\""
}
}]
}
},
"filter": {
"bool": {
"must": [{
"range": {
"过期时间": {
"from": ,
"to":
}
}
}]
}
}
}
},
"from":
}

结果1:

{
"took": ,
"timed_out": false,
"_shards": {
"total": ,
"successful": ,
"failed":
},
"hits": {
"total": 0,
"max_score": ,
"hits": []
......

但是,完全相同的查询语句,如果在 URL 中指定 type,那么过滤就 OK 了,,,

示例2:

URL: http://200.200.194.155:9200/index/my_type/_search
{
"query": {
"filtered": {
"query": {
"bool": {
"should": [{
"query_string": {
"query": "_type:\"my_type1\""
}
}]
}
},
"filter": {
"bool": {
"must": [{
"range": {
"过期时间": {
"from": ,
"to":
}
}
}]
}
}
}
},
"from":
}

结果2:

{
"took": ,
"timed_out": false,
"_shards": {
"total": ,
"successful": ,
"failed":
},
"hits": {
"total": ,
"max_score": ,
"hits": [
{
......

解决

确保相同字段的数据类型一致,,,

比如上面的问题,我删除了该字段类型为 string 的那个 type 就完全 OK 了。