首页 > ELK > elasticsearch用于html去标签化搜索
2019
07-12

elasticsearch用于html去标签化搜索

场景


elasticsearch用于html去标签化搜索:即在Index的时候忽略html tag,同时又存储了完整的html,在使用的时候可以正常读出来。


示例


假设我们给content字段自定义analyzer ,分别是:html_text_analyzer,html_keyword_analyzer


定义两种过滤html标记后,自动生成的没有html标签的index

PUT my_index
{
  "settings": { 
    "analysis": {
      "analyzer": {
        "html_text_analyzer": {
          "tokenizer": "standard",
          "char_filter": ["html_char_filter"]
        },
        "html_keyword_analyzer": {
          "tokenizer": "keyword",
          "filter":["trim"],
          "char_filter": ["html_char_filter"]
        }
      },
      "char_filter": {
        "html_char_filter": {
          "type": "html_strip"
        }
      }
    }
  },
  "mappings": {
    "properties": {
      "content":{
        "type": "text",
        "fields": {
          "html_text":{
            "search_analyzer": "simple",
            "analyzer":"html_text_analyzer",
            "type":"text"
          },
          "html_keyword":{
            "analyzer":"html_keyword_analyzer",
            "type":"text"
          }
        }
      }
    }
  }}

mappings 设置字段子类型,一个字段建立三种index (默认:analyzer,html_text,html_keyword),方便比较


查看刚才设置的mappings

GET my_index/_mapping


下面我们测试一下html_text_analyzer

//测试

POST my_index/_analyze
{
  "analyzer": "html_text_analyzer",
  "text": "<p>I&apos;m so <b>happy</b>!</p>"
}

// 返回结果

{
  "tokens" : [
    {
      "token" : "I'm",
      "start_offset" : 3,
      "end_offset" : 11,
      "type" : "<ALPHANUM>",
      "position" : 0
    },
    {
      "token" : "so",
      "start_offset" : 12,
      "end_offset" : 14,
      "type" : "<ALPHANUM>",
      "position" : 1
    },
    {
      "token" : "happy",
      "start_offset" : 18,
      "end_offset" : 27,
      "type" : "<ALPHANUM>",
      "position" : 2
    }
  ]
}

下面我们测试一下html_keyword_analyzer

POST my_index/_analyze
{
  "analyzer": "html_keyword_analyzer",
  "text": "<p>I&apos;m so <b>happy</b>!</p>"
}

// 返回结果  去除html标记,全文被索引为一个keyword
{
  "tokens" : [
    {
      "token" : "I'm so happy!",
      "start_offset" : 0,
      "end_offset" : 32,
      "type" : "word",
      "position" : 0
    }
  ]
}


录入数据测试比较一下:

//录入数据 带span标记
POST my_index/_doc
{
  "content":"<span>I&apos;m so <b>happy</b>!</span>"
}


//查询my_index结果,原始的text类型使用默认analyzer,查询span,能返回结果是因为span也被索引了

POST my_index/_search
{
  "query": {
    "match": {
      "content": "span"
    }
   }
}
  
  
//查询使用html_text_analyzer建立的索引中的span,无返回结果结果,说明html标记没有被索引

POST my_index/_search
{
  "query": {
    "match": {
      "content.html_text": "span"
    }
   }
}
  
  
//查询使用html_text_analyzer建立的索引中的happy,能返回结果,html中text被正常索引

POST my_index/_search
{
  "query": {
    "match": {
      "content.html_text": "happy"
    }
   }
}
  
// 查询使用html_keyword_analyzer建立的索引中的happy,无返回结果,因为这里要用keyword的查询语法

POST my_index/_search
{
  "query": {
    "match": {
      "content.html_keyword": "happy"
    }
   }
}


本文》有 0 条评论

留下一个回复