ElasticSearch中的Buggy Regexp查询

时间:2015-07-24 20:33:00

标签: regex elasticsearch

我已插入raw_id字段等于1.2.3.04ABC的文档,并且我正在尝试构建正则表达式查询以搜索ES中的文档。我使用以下查询:

curl -X POST 'http://localhost:9200/hello/world/_search' -d '{
"query": {
    "regexp": {
        "raw_id": "1\\.2\\.3\\.04ABC" 
        }
    }
}' 

返回结果空结果

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

另一方面,当我使用稍加修改的查询

curl -X POST 'http://localhost:9200/hello/world/_search' -d '{
"query": {
    "regexp": {
        "raw_id": "1\\.2\\.3.*" 
        }
    }
}' 

我得到了非空的结果:

{
    "_shards": {
        "failed": 0,
        "successful": 5,
        "total": 5
    },
    "hits": {
        "hits": [
            {
                "_id": "adfafadfafa",
                "_index": "hello",
                "_score": 1.0,
                "_source": {
                    "raw_id": "1.2.3.04ABC"
                },
                "_type": "world"
            }
        ],
        "max_score": 1.0,
        "total": 1
    },
    "timed_out": false,
    "took": 2
}

有人可以帮我理解为什么第一个查询无效吗?

1 个答案:

答案 0 :(得分:1)

我的猜测是,您的raw_id字段是经过分析的字符串,而应该是not_analyzed。我已使用以下映射与一个已分析的字符串字段id和另一个not_analyzed字符串字段raw_id

curl -XPUT 'http://localhost:9200/hello' -d '{
  "mappings": {
    "world": {
      "properties": {
        "id": {
          "type": "string"
        },
        "raw_id": {
          "type": "string",
          "index": "not_analyzed"
        }
      }
    }
  }
}'

然后我将以下文件编入索引:

curl -XPUT 'http://localhost:9200/hello/world/1' -d '{
  "id": "1.2.3.04ABC",
  "raw_id": "1.2.3.04ABC"
}'

现在上面的查询,如果我搜索id字段,我没有点击:

curl -XPOST 'http://localhost:9200/hello/world/_search' -d '{
"query": {
    "regexp": {
        "id": "1\\.2\\.3\\.04ABC" 
        }
    }
}'
=> 0 hits KO

但是,当我搜索raw_id字段时,我确实遇到了一个问题:

curl -XPOST 'http://localhost:9200/hello/world/_search' -d '{
"query": {
    "regexp": {
        "raw_id": "1\\.2\\.3\\.04ABC" 
        }
    }
}'
=> 1 hit OK

使用您的第二个查询,我会得到每个字段的匹配:

curl -XPOST 'http://localhost:9200/hello/world/_search' -d '{
"query": {
    "regexp": {
        "id": "1\\.2\\.3.*" 
        }
    }
}'
=> 1 hit OK

curl -XPOST 'http://localhost:9200/hello/world/_search' -d '{
"query": {
    "regexp": {
        "raw_id": "1\\.2\\.3.*" 
        }
    }
}'
=> 1 hit OK