一.分析器主要有两种情况会被使用:


第一种是插入文档时,将text类型的字段做分词然后插入倒排索引,
第二种就是在查询时,先对要查询的text类型的输入做分词,再去倒排索引搜索

如果想要让 索引 和 查询 时使用不同的分词器,ElasticSearch也是能支持的,只需要在字段上加上search_analyzer参数

在索引时,只会去看字段有没有定义analyzer,有定义的话就用定义的,没定义就用ES预设的

在查询时,会先去看字段有没有定义search_analyzer,如果没有定义,就去看有没有analyzer,再没有定义,才会去使用ES预设的

二.几种搜索机制的比较

关键词keyword类型text类型是否支持分词
term完全匹配查询条件中关键词不会被分词,它必须整个关键词和document中的某个分词匹配,才能搜索到,多个分词时必须连续,顺序不能颠倒。
match完全匹配match分词结果和text的分词结果有相同的即可
match_phrase完全匹配match_phrase的分词结果必须在text字段分词中都包含,而且顺序必须相同,而且必须都是连续的。
query_string    完全匹配query_string中和match_string基本一样,区别时它不考虑顺序

测试:

在这里设置分本分词器为标准分词器,搜索分词器为ik,采用match搜索,因为ik分词器将共产党三个字分此后还是共产党,在标准分词器分过的文档中匹配不到,具体演示如下

   //创建索引:

//创建索引
put /test10
{
  "mappings":{
      "properties":{
         "name":{
           "type":"text",
           "store":true,
           "analyzer":"standard", 
          "search_analyzer": "ik_smart"
         },
          "add": {
           "type": "text",
            "store":true,
           "analyzer":"ik_smart",
           "search_analyzer": "ik_smart"
         }
      }
  }
}

//添加文档

PUT /test10/_doc/1
{
  "name":"我是中国共产党",
  "add":"我是中国共产党"
}

// Ik分词器测试
GET _analyze
{
  "analyzer": "ik_smart",
  "text": "共产党"
 }

结果:
{
  "tokens" : [
    {
      "token" : "共产党",
      "start_offset" : 0,
      "end_offset" : 3,
      "type" : "CN_WORD",
      "position" : 0
    }
  ]
}

//标准分词器测试
GET _analyze
{
  "analyzer": "standard",
  "text": "我是中国共产党"
}

结果:
{
  "tokens" : [
    {
      "token" : "我",
      "start_offset" : 0,
      "end_offset" : 1,
      "type" : "<IDEOGRAPHIC>",
      "position" : 0
    },
    {
      "token" : "是",
      "start_offset" : 1,
      "end_offset" : 2,
      "type" : "<IDEOGRAPHIC>",
      "position" : 1
    },
    {
      "token" : "中",
      "start_offset" : 2,
      "end_offset" : 3,
      "type" : "<IDEOGRAPHIC>",
      "position" : 2
    },
    {
      "token" : "国",
      "start_offset" : 3,
      "end_offset" : 4,
      "type" : "<IDEOGRAPHIC>",
      "position" : 3
    },
    {
      "token" : "共",
      "start_offset" : 4,
      "end_offset" : 5,
      "type" : "<IDEOGRAPHIC>",
      "position" : 4
    },
    {
      "token" : "产",
      "start_offset" : 5,
      "end_offset" : 6,
      "type" : "<IDEOGRAPHIC>",
      "position" : 5
    },
    {
      "token" : "党",
      "start_offset" : 6,
      "end_offset" : 7,
      "type" : "<IDEOGRAPHIC>",
      "position" : 6
    }
  ]
}

//查询测试
GET /test10/_doc/_search
{
  "query":
  {
    "match":{
      "name": "共产党"
    }
  }
}

结果:
{
  "took" : 1,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 0,
      "relation" : "eq"
    },
    "max_score" : null,
    "hits" : [ ]
  }
}

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐