【ES】match_phrase与regexp

刚开始接触es,由于弄不清楚match_phrase和regexp导致很多查询结果与预想的不同。在这整理一下。

regexp:针对的是单个词项

match_phrase:针对的是多个词项的相对位置

它们的查询结果跟分析器分词的方式有很大关系。

比如,我有两个字符串"HELLO-world" 和 "hello.WORLD",字段名称是title。

针对"HELLO-world",看下面两个语句。第二个是可以匹配的,第一个不可以。

{ "regexp": { "title": "hello-w.*" }} 
{ "match_phrase": { "title": "hello world" }}

分析一下,可以看到,HELLO-world被分为了两个单词,hello和world。

-GET _analyze
{        
    "field": "title",
    "text": "HELLO-world"
}
---------------------------
{
  "tokens" : [
    {
      "token" : "hello",
      "start_offset" : 0,
      "end_offset" : 5,
      "type" : "<ALPHANUM>",
      "position" : 0
    },
    {
      "token" : "world",
      "start_offset" : 6,
      "end_offset" : 11,
      "type" : "<ALPHANUM>",
      "position" : 1
    }
  ]
}

首先,es是没有大写的,所有的字符都被转换成了小写。其次,"-"字符丢失了。

regexp是针对单个词项的,无论是hello还是world,都不符合正则条件,故没有匹配。

match_phrase是针对多个词项的。首先match_phrase的"hello world"被分为了hello和world两个单词,然后这两个单词在title的分词中都可以找到,并且相对位置满足条件,故语句可以匹配。

再看 "hello.WORLD"

{ "regexp": { "title": "hello\.w.*" }} 
{ "match_phrase": { "title": "hello world" }}

结果是,第一个可以匹配,而第二个不能。

原因看分词结果:

-GET_analyze
{        
    "field": "title",
    "text": "hello.WORLD"
}
-------------------------------
{
  "tokens" : [
    {
      "token" : "hello.world",
      "start_offset" : 0,
      "end_offset" : 11,
      "type" : "<ALPHANUM>",
      "position" : 0
    }
  ]
}

坑爹的情况出现了,"."并不会被切分,整个"hello.world"被视作了一个词项。

match_phrase在词项中查找hello和world都查找不到,故不会匹配

regexp则能找到一个满足正则表达式的词项,故可以匹配。

ES的分词处理非常重要,很大的影响了查询结果!

原文地址:https://www.cnblogs.com/dplearning/p/6994643.html