一:空字符串的坑
使用Elasticsearch時間比較長了仗嗦,很多時候停留在會使用階段捞慌,直到昨天遇到一個空字符串的問題淤堵,思考了很久寝衫,發(fā)現其實很多東西只是停留在認知階段,下面分析下坑的來源以及解決辦法拐邪。
二:場景:
我有一個content字段配置了分詞,需要進行搜索,type設置的是text慰毅,
并不是我所期待的結果
查了資料,[Elasticsearch Reference [7.9] ? Mapping ? Mapping parameters ? null_value
]https://www.elastic.co/guide/en/elasticsearch/reference/current/null-value.html
其實發(fā)現這個并不是自己想要的結果,但是為了驗證怎么才能查出來是空字符串的數據這個問題,猜到了大概跟mapping中type設置應該有關系,因此嘗試默認mapping的方式扎阶,這時候發(fā)現出來的結果才是正確的汹胃,但是有一個問題,分詞問題东臀,因此在默認mapping基礎上嘗試了加上分詞設置着饥,具體操作如下
PUT /index_001/
{
"mappings": {
"properties": {
"id": {
"type": "keyword"
},
"content": {
"type": "text",
"analyzer": "ik_max_word",
"search_analyzer": "ik_smart"
}
}
}
}
POST /index_001/_doc/1
{
"id":"1",
"content":"華為手機"
}
POST /index_001/_doc/2
{
"id":"2",
"content":""
}
POST /index_001/_doc/3
{
"id":"3",
"content":"華為電腦"
}
GET /index_001/_search
{
"query": {
"match": {
"content.keyword": "華為電腦"
}
}
}
GET /index_001/_mapping
GET /index_001/_search
{
"query": {
"bool": {
"must_not": [
{
"exists": {
"field": "summary"
}
},
{
"match": {
"content": ""
}
}
]
}
}
}
PUT /index_002
GET /index_002/_mapping
POST /index_002/_doc/1
{
"id":"1",
"content":"華為手機"
}
POST /index_002/_doc/2
{
"id":"2",
"content":""
}
POST /index_002/_doc/3
{
"id":"3",
"content":"華為電腦"
}
GET /index_002/_search
{
"query": {
"match": {
"content": "華為"
}
}
}
GET /index_002/_search
{
"query": {
"match": {
"content.keyword": "華為電腦"
}
}
}
GET /index_002/_search
{
"query": {
"bool": {
"must_not": [
{
"exists": {
"field": "summary"
}
},
{
"term": {
"content.keyword": ""
}
}
]
}
}
}
PUT /index_003/
{
"mappings": {
"properties": {
"id": {
"type": "keyword"
},
"content": {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
},
"analyzer": "ik_max_word",
"search_analyzer": "ik_smart"
}
}
}
}
POST /index_003/_analyze
{
"analyzer": "ik_max_word",
"text": "華為手機"
}
POST /index_003/_doc/1
{
"id":"1",
"content":"華為手機"
}
POST /index_003/_doc/2
{
"id":"2",
"content":""
}
POST /index_003/_doc/3
{
"id":"3",
"content":"華為電腦"
}
GET /index_003/_search
{
"query": {
"match": {
"content.keyword": "華為電腦"
}
}
}
GET /index_003/_search
{
"query": {
"term": {
"content.keyword": "華為"
}
}
}
GET /index_003/_search
{
"query": {
"bool": {
"must_not": [
{
"exists": {
"field": "summary"
}
},
{
"term": {
"content.keyword": ""
}
}
]
}
}
}
以上的操作的全部過程,結果如下
image.png
三:坑的由來
在go中content這個字段在解析的時候沒有拿到想要的數據惰赋,因此采用了默認值宰掉,這才出現了上面的問題,因此建議在不確定情況的時候mapping設置成第三種形式最為穩(wěn)妥赁濒,或者字符串的默認值給一個其他的不為空字符串的值即可