在Elasticsearch中进行多字段和多条件搜索非常简单。可以使用布尔查询和过滤器来设置多个条件,并且可以根据需要设置多个字段。
下面是实现多字段和多条件搜索的步骤:
{
"query": {
"multi_match": {
"query": "关键词",
"fields": ["title", "content"]
}
}
}
{
"query": {
"bool": {
"must": [
{ "match": { "city": "北京" }},
{ "match": { "city": "上海" }}
]
}
}
}
{
"query": {
"bool": {
"must": { "match": { "tags": "技术" }},
"filter": { "range": { "publish_date": { "gte": "2019-01-01" }}}
}
}
}
在以上查询结果中,高亮显示出现的关键词,可以通过添加highlight选项实现。
例如,在查找标题和内容字段时,可以使用以下查询来启用高亮:
{
"query": {
"multi_match": {
"query": "关键词",
"fields": ["title", "content"]
}
},
"highlight": {
"fields": {
"title": {},
"content": {}
}
}
}
这样就可以将匹配的关键词高亮显示在搜索结果中了。