2015-09-25 131 views
1

我需要将内容与单词列表(对于淫秽词匹配)进行匹配。作为我需要的一个简单例子。Elasticsearch搜索其他字段

{ 
    "bool": { 
    "should": [ 
     { "term": { "content": "word1" }}, 
     { "term": { "content": "word2" }} 
      : 
     { "term": { "content": "word1001" }} 
    ] 
    } 
} 

我找“word1001”是在另一种类型的另一个领域上市“字词1”,“字词1”,......这些话。

我需要实现的是类似

{ 
    "bool": { 
    "should": [ 
     { "term": { "content": banned_words.word }}, 
    ] 
    } 
} 

我需要匹配数量可能为成千上万的话,上述布尔似乎不是最有效的。但是,我找不到替代方案。

+1

我想你必须为此写一个自定义匹配器。无论如何,1000个元素的香草布尔查询不会有效。 – Ashalynd

+0

最初的请求会很慢,但是如果您可以使用过滤器而不是查询禁止的单词列表,那么该过滤器将被缓存(使后续执行非常便宜!) –

回答

0

另一种在查询时不匹配所有不良词的方法是在索引时使用synonym token filter来匹配这些词并标记包含不良词的文档。

所有你需要做的是存储在文件系统中的文件你的坏字(Elasticsearch主目录):

analysis/badwords.txt

word1 => BADWORD  <--- pick whatever you want the badword to be replaced with 
word2 => BADWORD 
... 
word1000 => BADWORD 

那么你的索引设置需要使用synonym令牌过滤

curl -XPUT localhost:9200/my_index -d '{ 
    "settings" : { 
     "analysis" : { 
      "analyzer" : { 
       "badwords" : { 
        "tokenizer" : "whitespace", 
        "filter" : ["synonym"] 
       } 
      }, 
      "filter" : { 
       "synonym" : { 
        "type" : "synonym", 
        "synonyms_path" : "analysis/badwords.txt" 
       } 
      } 
     } 
    }, 
    "mappings": { 
     "my_type": { 
      "properties": { 
       "content": { 
        "type": "string", 
        "index_analyzer": "badwords" 
       } 
      } 
     } 
    } 
}' 

然后,当你的索引文档用content场包含一些BA d字符与您的badwords.txt文件中的字符相匹配,它会被您在同义词文件中选择的替换字正确替换。

curl -XPOST 'localhost:9200/my_index/_analyze?analyzer=badwords&pretty' -d 'you are a word2' 
{ 
    "tokens" : [ { 
    "token" : "you", 
    "start_offset" : 0, 
    "end_offset" : 3, 
    "type" : "word", 
    "position" : 1 
    }, { 
    "token" : "are", 
    "start_offset" : 4, 
    "end_offset" : 7, 
    "type" : "word", 
    "position" : 2 
    }, { 
    "token" : "a", 
    "start_offset" : 8, 
    "end_offset" : 9, 
    "type" : "word", 
    "position" : 3 
    }, { 
    "token" : "BADWORD", 
    "start_offset" : 10, 
    "end_offset" : 14, 
    "type" : "SYNONYM", 
    "position" : 4 
    } ] 
} 
+0

谢谢@Val。让我有机会看到这个解决方案如何与我的实现相匹配。我不一定要实施单词替换,但是要标记文档(在分类网站中,有人可能会放弃一只“可爱的猫猫”),这会引发各种标志。 – crafter

+1

好的,我看到,也可以不替换badword,而只是用同义词映射来标记它,比如'word1 => word1,BADWORD'。这样做可以保留潜在的坏道,但也可以在它后面添加“BADWORD”令牌。 – Val