一次从两个字段中查询同一个搜索词,比如从title和content中进行查询,另外指定active字段的值必须为true(一般代表该文档未被删除或隐藏):
GET /docwrite2/_search
{
"query": {
"bool": {
"must": [
{
"multi_match": {
"query": "跳板机",
"fields": [
"title", //搜索字段1
"content" //搜索字段2
],
"analyzer": "ik_smart",
"type": "best_fields" //假设你想匹配最佳字段,可以根据需要选择其他类型
}
}
],
"filter": [
{
"term": {
"active": true
}
}
]
}
}
}
只需略微修改一下,就可以提高title字段的权重,根据生产实际,我们认为标题的重要性显然是高于正文内容的,因此权重相对提高5倍。
GET /docwrite2/_search
{
"query": {
"bool": {
"must": [
{
"multi_match": {
"query": "跳板机",
"fields": [
"title^5", // 提高title字段的权重,假设设置为5倍
"content" // content字段使用默认权重1
],
"analyzer": "ik_smart",
"type": "best_fields"
}
}
],
"filter": [
{
"term": {
"active": true
}
}
]
}
}
}
在上面的查询中,title^5表示title字段的权重被设置为5,这意味着title字段的匹配将对最终得分产生更大的影响。你可以根据需要调整这个值。content字段没有指定boost值,因此它将使用默认权重1。
请注意,boost值只是相对权重,而不是绝对得分。它用于在字段之间分配更多的“重要性”,但实际的得分还会受到文档内容、字段分析和查询类型等多种因素的影响。
best_fields类型会返回匹配最佳字段的文档,并考虑字段的权重。如果你想要所有匹配字段都对得分有所贡献,你可以使用cross_fields或most_fields等其他类型。
上面的查询中的filter是一个数组,只需要往其中新增一个range条件即可:
{
"range": {
"updatetime": {
"gte": 1672531200000, //开始时间戳,例如:2023-01-01T00:00:00Z的时间戳
"lte": 1675113599000 //结束时间戳,例如:2023-01-31T23:59:59Z的时间戳
}
}
}
我需要把指定文档的一个值进行更新,执行如下命令将该文档的active值改为true:
POST /docwrite2/_update/change-this-id-6163dbf
{
"script": {
"source": "ctx._source.active = params.newActive",
"params": {
"newActive": true
}
}
}
对搜索到的关键词高亮展示对用户是很友好的,可以通过以下方法实现:
GET /docwrite2/_search
{
"query": {
"bool": {
"must": [
{
"multi_match": {
"query": "的",
"fields": [
"title^5",
"content"
],
"analyzer": "ik_smart",
"type": "best_fields"
}
}
],
"filter": [
{
"term": {
"active": true
}
}
]
}
},
"highlight": {
"fields": {
"content": {
"fragment_size": 100,
"number_of_fragments": 3,
"pre_tags": [
""
],
"post_tags": [
""
]
}
}
},
"_source": {
"excludes": ["content"]
}
}
上述查询中的高亮逻辑主要是其中的highlight属性控制:

Elasticsearch的响应将包含一个highlight字段,其中包含了被高亮的文本片段。这个返回结果需要前端逻辑处理和渲染才能展示高亮的效果。