确实http://www.google.com 会被标准分析器标记为http 和www.google.com,因此google.com 将找不到。
因此,单独的标准分析器在这里没有帮助,我们需要一个可以正确转换 URL 标记的标记过滤器。如果您的 text 字段仅包含 URL,则另一种方法是使用 UAX Email URL tokenizer,但由于该字段可以包含任何其他文本(即用户 cmets),因此它将不起作用。
幸运的是,有一个名为 analysis-url 的新插件提供了 URL 令牌过滤器,这正是我们所需要的(在 small modification 请求之后,感谢 @jlinn ;-))
首先,你需要安装插件:
bin/plugin install https://github.com/jlinn/elasticsearch-analysis-url/releases/download/v2.2.0/elasticsearch-analysis-url-2.2.0.zip
然后,我们可以开始玩了。我们需要为您的 text 字段创建适当的分析器:
curl -XPUT localhost:9200/test -d '{
"settings": {
"analysis": {
"filter": {
"url_host": {
"type": "url",
"part": "host",
"url_decode": true,
"passthrough": true
}
},
"analyzer": {
"url_host": {
"filter": [
"url_host"
],
"tokenizer": "whitespace"
}
}
}
},
"mappings": {
"url": {
"properties": {
"text": {
"type": "string",
"analyzer": "url_host"
}
}
}
}
}'
使用此分析器和映射,我们可以正确索引您希望能够搜索的主机。例如,让我们使用我们的新分析器分析字符串blabla bla http://www.google.com blabla。
curl -XGET 'localhost:9200/urls/_analyze?analyzer=url_host&pretty' -d 'blabla bla http://www.google.com blabla'
我们将获得以下代币:
{
"tokens" : [ {
"token" : "blabla",
"start_offset" : 0,
"end_offset" : 0,
"type" : "word",
"position" : 0
}, {
"token" : "bla",
"start_offset" : 0,
"end_offset" : 0,
"type" : "word",
"position" : 1
}, {
"token" : "www.google.com",
"start_offset" : 0,
"end_offset" : 0,
"type" : "word",
"position" : 2
}, {
"token" : "google.com",
"start_offset" : 0,
"end_offset" : 0,
"type" : "word",
"position" : 3
}, {
"token" : "com",
"start_offset" : 0,
"end_offset" : 0,
"type" : "word",
"position" : 4
}, {
"token" : "blabla",
"start_offset" : 0,
"end_offset" : 0,
"type" : "word",
"position" : 5
} ]
}
如您所见,http://www.google.com 部分将被标记为:
www.google.com
-
google.com 即您所期望的
com
所以现在如果您的searchString 是google.com,您将能够找到所有具有包含google.com(或www.google.com)的text 字段的文档。