当我们把我们的文档导入到Elasticsearch中,有时我们希望知道所输入的语言是什么?我们甚至可以针对不同的语言来做不同的处理。那么我们有什么方法呢?
Elastic的Alexander Reelsen,也就是我的同事,写了一个叫做Langdetect Ingest Plugin。这个plugin可以帮我们来检查所输入文字的语言。
在今天的这篇文章中,我来介绍如何使用这个plugin。
安装
首先,我们可以在地址:https://github.com/spinscale/elasticsearch-ingest-langdetect/releases 找到和您Elasticsearch像匹配的版本。针对我的Elasticsearch 7.5.0,我选择7.5.1的发行版来进行安装。我们首先进入到Elasticsearch的安装目录,然后打入如下的命令:
./bin/elasticsearch-plugin install https://github.com/spinscale/elasticsearch-ingest-langdetect/releases/download/7.5.0.1/ingest-langdetect-7.5.0.1.zip
等我们安装好上面的inget plugin,我们可以打入如下的命令:
./bin/elasticsearch-plugin list
如果已经被成功安装好,我们可以看到已经安装好的插件:
安装好这个插件后,请务必要重新启动Elasticsearch才可以起作用。
使用 Language Ingest Plugin
首先,我们在Kibana的Dev tools中打入如下的命令:
PUT _ingest/pipeline/langdetect-pipeline
{
"description": "A pipeline to do whatever",
"processors": [
{
"langdetect": {
"field": "my_field",
"target_field": "language"
}
}
]
}
上面的命令创建一个叫做langdetect-pipeline。
接下来,我们使用如下的命令来检查我们的pipeline是否工作:
PUT my-index/_doc/1?pipeline=langdetect-pipeline
{
"my_field": "This is hopefully an english text, that will be detected."
}
我们使用如下的命令来查询我们的文档:
GET my-index/_doc/1
返回的结果是:
{
"_index" : "my-index",
"_type" : "_doc",
"_id" : "1",
"_version" : 3,
"_seq_no" : 10,
"_primary_term" : 1,
"found" : true,
"_source" : {
"my_field" : "This is hopefully an english text, that will be detected.",
"language" : "en"
}
}
在上面的返回中,我们可以看到在_source里多一个language的字段,而且它的值为“en”,也就是English。
现在我们来试一个中问的例子:
PUT my-index/_doc/2?pipeline=langdetect-pipeline
{
"my_field": "我在这里"
}
同样我们来查询刚上输入的文档:
GET my-index/_doc/2
返回的结果是:
{
"_index" : "my-index",
"_type" : "_doc",
"_id" : "2",
"_version" : 8,
"_seq_no" : 11,
"_primary_term" : 1,
"found" : true,
"_source" : {
"my_field" : "我在这里",
"language" : "zh-cn"
}
}
在上面,我们可以看到language的值为 “zh-cn”。
我们可以利用如下的代码创建几个文档:
PUT my-index/_doc/1?pipeline=langdetect-pipeline
{
"my_field": "Good morning"
}
PUT my-index/_doc/2?pipeline=langdetect-pipeline
{
"my_field": "Te quiero"
}
PUT my-index/_doc/3?pipeline=langdetect-pipeline
{
"my_field": "早上好"
}
上面的文档都是 “早上好” 分别用英文,西班牙及英文。 我们可以通过如下的方式来得到我们想要的语言的结果:
GET my-index/_search
{
"query": {
"term": {
"language.keyword": {
"value": "zh-cn"
}
}
}
}
返回的结果是:
{
"took" : 0,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : 1.2039728,
"hits" : [
{
"_index" : "my-index",
"_type" : "my-type",
"_id" : "3",
"_score" : 1.2039728,
"_source" : {
"my_field" : "早上好",
"language" : "zh-cn"
}
}
]
}
}
在未来,我们可以使用Elasticsearch所提供的语言检测https://github.com/elastic/elasticsearch/pull/50680
注意:由于一些原因,目前这个插件还是有一些bug:https://github.com/spinscale/elasticsearch-ingest-langdetect/issues/9