es: 临时指定一部分doc的排序靠前

一,代码

# es分页搜索,通过关健词列表
def es_topic_search_by_list(qk_list):
    should_list = []
    for qk in qk_list:
        qk_one = qk.strip()
        if qk_one == '':
            continue
        one_q1 = { # 强化连续词匹配
                        'match_phrase': {
                            'title': {
                                'query': qk_one,
                                "analyzer": "ik_max_word",
                                'boost': 5
                            }
                        }
                 }
        should_list.append(one_q1)
        one_q2 = { # 强化连续词匹配
                        'match_phrase': {
                            'summary': {
                                'query': qk_one,
                                "analyzer": "ik_max_word",
                                'boost': 5
                            }
                        }
                 }
        should_list.append(one_q2)

    # 指定subject的id
    # 得到当前环境
    if current_app.config['MODE'] == 'prod':
        subject_list = [37,42,40,39,43,41,7,6,38,32,30]
    else:
        subject_list = [9]


    subject_cond = {
        "terms": {
            "subject_id": subject_list,
            "boost": 100  # 赋予极高权重,使其直接置顶
        }
    }
    should_list.append(subject_cond)

    body = {
        # 'min_score': 0.5,   #暂时取消score的限制
        'query': {
            'bool': {
                'should': should_list,
                'minimum_should_match': 1,

            },

        },
        'from': 0,
        'size': 1000,
    }

    es = get_es()

    res = {}
    hit_rids = []
    hit_response = es.search(
        index=current_app.config['your_index_name'],
        body=body
    )

二,说明:

subject_id in [1, 2, 3] 作为一个 should 条件,并赋予一个很高的 boost(权重值)。
由于 should 满足时会加分,不满足时不扣分,因此这三个 ID 的文档得分会远高于其他文档,自动排在最前。
 
posted @ 2026-07-14 21:52  刘宏缔的架构森林  阅读(4)  评论(0)    收藏  举报