zoukankan      html  css  js  c++  java
  • 【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的分词处理非常重要,很大的影响了查询结果!

  • 相关阅读:
    水晶报表设计--基本概念
    微信公众平台开发小结
    CCF计算机职业认证考试
    Linux 命令
    百度搜索引擎的一些技巧
    Windows的一些操作命令
    Eclipse:写jsp 出现的一些问题
    操作系统(基本问题)
    C语言编程技巧(注意点)
    mysql命令报错问题
  • 原文地址:https://www.cnblogs.com/dplearning/p/6994643.html
Copyright © 2011-2022 走看看