以下是我的elasticsearch映射
{
"metadata" : {
"mappings" : {
"properties": {
"id": {"type":"keyword"},
"title": {"type":"keyword"},
"created": {"type":"date"},
"modified": {"type":"date"},
"keyword": {"type":"keyword"},
"description": {"type":"text"}
}
}
}
}
下面是我的ES查询,根据用户对多个字段的查询来检索数据,限制在前5名,按修改日期排序,只显示标题& 描述字段。这个查询完全按照我的期望工作。
GET /_search
{
"query": {
"multi_match" : {
"query" : "UK House Price Index",
"fields" : ["title", "keyword", "description"]
}
},
"size": 5,
"_source": ["title", "description"],
"sort": {"modified": "asc"}
}
我想将描述字段的响应限制在100个字符以内。我是ES的新手。谁能告诉我如何有效地完成这个任务?
您可以使用 highlighting
的相关部分,以获得匹配的 description
. 它得到了... fragment_size
设置,这基本上是你想要的字符串连接,有趣的是,默认值为100。
POST long_desc/_doc
{"title":"UK House Price Index","keyword":"UK House Price Index","description":"APM automatically collects in-depth performance metrics and errors from inside your applications. Ingest logs UK House Price Index from popular data sources and easily visualize in preconfigured dashboards."}
GET long_desc/_search
{
"query": {
"multi_match": {
"query": "UK House Price Index",
"fields": [
"title",
"keyword",
"description"
]
}
},
"size": 5,
"_source": [
"title"
],
"sort": {
"modified": "asc"
},
"highlight": {
"pre_tags": "",
"post_tags": "",
"fragment_size": 1,
"fields": {
"description": {
"fragment_size": 100,
"number_of_fragments": 1,
"fragmenter": "span"
}
}
}
}
产生
[
{
"_index":"long_desc",
"_type":"_doc",
"_id":"zSWAwnEBPAbzy1R_Uk-I",
"_score":null,
"_source":{
"title":"UK House Price Index"
},
"highlight":{
"description":[
"Ingest logs UK House Price Index from popular data sources and easily visualize in preconfigured dashboards"
]
}
...
}
]
顺便说一下 pre_
& post_tags
默认为 <em>
所以你的前台不需要做任何后期处理,呃,突出显示匹配的内容。我选择了空字符串来保持 description
干净。