我有一个字符串,我想用一个表的行值来搜索这个字符串中最长的匹配值。在SQL中,这个查询可以正常工作。
SELECT model, LENGTH(model) AS size
FROM models
WHERE 'Acer Aspire 3 A315-42' LIKE CONCAT('%', model, '%')
ORDER BY size DESC
LIMIT 1;
但速度很慢 Elasticsearch可以在索引中找到查询匹配,但我需要在查询中找到索引匹配。在elasticsearch中有什么解决办法吗?
脚本字段可以用来对文本的长度进行排序。更好的选择是同时索引文本长度并在该字段上排序。
数据。
"hits" : [
{
"_index" : "index16",
"_type" : "_doc",
"_id" : "QNLN5HEB9UrRQjNWOLGw",
"_score" : 1.0,
"_source" : {
"model" : "Acer Aspire 3 A315-42 aa"
}
},
{
"_index" : "index16",
"_type" : "_doc",
"_id" : "QdLN5HEB9UrRQjNWQLFu",
"_score" : 1.0,
"_source" : {
"model" : "Acer Aspire 3 A315-42"
}
}
]
查询。
{
"query": {
"match": {
"model": "Acer Aspire 3 A315-42"
}
},
"sort": [
{
"_script":{
"script": "doc['model.keyword'].value.length()",-->script to return length
"type": "number",
"order": "desc"
}
}
],
"size": 1 --> top 1
}
结果。
"hits" : [
{
"_index" : "index16",
"_type" : "_doc",
"_id" : "QNLN5HEB9UrRQjNWOLGw",
"_score" : null,
"_source" : {
"model" : "Acer Aspire 3 A315-42 aa"
},
"sort" : [
25.0
]
}
]