elasticsearch-search-relevance
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseElasticsearch Search Relevance
Elasticsearch 搜索相关性
Improve full-text search results on content and catalog indices. Diagnose the mapping and current query, choose the
right relevance lever (query rules for deterministic pinning vs multi_match and field boosts for organic ranking), apply
the change, and verify top hits before reporting success.
<!-- begin-partial: preamble -->提升内容和目录索引的全文搜索结果。诊断映射和当前查询,选择合适的相关性调节手段(确定性固定结果使用查询规则,自然排序优化使用multi_match和字段权重),应用更改并验证顶部结果后再报告成功。
<!-- begin-partial: preamble -->Environment Configuration
环境配置
This skill executes Elasticsearch operations through the CLI. If the
CLI is not installed, tell the user what it is needed for. Do
not guess credentials, call the HTTP API directly, or attempt other workarounds.
elasticelasticThis skill references operations in HTTP-shorthand form (e.g., , , ,
, ). The Operations table at the end of this document
maps each shorthand to the equivalent CLI command — always use the CLI rather than calling the HTTP API
directly.
<!-- end-partial: preamble -->GET /GET /_cat/indicesGET /{index}/_mappingGET /{index}/_settings/index.modePOST /_queryelastic本技能通过 CLI执行Elasticsearch操作。如果未安装 CLI,请告知用户其用途。请勿猜测凭证、直接调用HTTP API或尝试其他变通方法。
elasticelastic本技能以HTTP简写形式引用操作(例如、、、、)。本文档末尾的操作表格将每个简写映射为等效的 CLI命令——请始终使用CLI而非直接调用HTTP API。
<!-- end-partial: preamble -->GET /GET /_cat/indicesGET /{index}/_mappingGET /{index}/_settings/index.modePOST /_queryelasticScope
适用范围
This skill covers Query DSL relevance on indices with (and optional ) fields — product catalogs,
documentation, knowledge bases. It uses for evaluation and query-rules APIs for pinned or
excluded documents.
textkeywordPOST /{index}/_searchOut of scope:
- ES|QL search () — use the
POST /_queryskill.elasticsearch-esql - Semantic / vector / hybrid retrieval — different field types and retrievers.
- Sorting by price, date, or popularity instead of fixing text relevance unless the user explicitly wants non-relevance ordering.
本技能涵盖带有(可选)字段的索引上的Query DSL相关性优化——适用于产品目录、文档、知识库。使用进行评估,使用查询规则API处理固定或排除的文档。
textkeywordPOST /{index}/_search不适用场景:
- ES|QL搜索()——请使用
POST /_query技能。elasticsearch-esql - 语义/向量/混合检索——涉及不同的字段类型和检索器。
- 按价格、日期或人气排序(而非修复文本相关性),除非用户明确要求非相关性排序。
Relevance levers
相关性调节手段
| User intent | Lever | APIs |
|---|---|---|
| Always show document X first for query Q | Query rules — | |
| Hide specific documents for query Q | Query rules — | Same |
| Better ranking for open-ended text queries | | |
| Tokens not matching user language | Operator, | |
Decision rule: If the user names a document that must rank first for a specific query, use query rules. If results
are generally weak for a phrase, tune the organic query from the mapping. Do not simulate pinning with extreme boosts,
, or sort clauses.
function_score| 用户意图 | 调节手段 | API |
|---|---|---|
| 针对查询Q始终将文档X置于首位 | 查询规则—— | |
| 针对查询Q隐藏特定文档 | 查询规则—— | 同上 |
| 优化开放式文本查询的排名 | 在映射的 | |
| 分词与用户语言不匹配 | 运算符、 | |
决策规则:如果用户指定某文档必须在特定查询中排名第一,则使用查询规则。如果某短语的整体结果表现不佳,则基于映射优化自然查询。请勿使用极端权重、或排序子句模拟固定效果。
function_scoreProcess
流程
-
Inspect the mapping and current query. Callto confirm connectivity. When the index is unknown, narrow candidates with
GET /, then callGET /_cat/indices.GET /{index}/_mappingFrom the mapping, list everyfield (e.g.,text,title) and everydescriptionfield used for filters (keyword,brand). Note which fields are short (precision) vs long (recall). Read the user's current search body if provided — identify which fields it queries and whether it already usescategory,rule, or single-fieldmulti_match.matchDecision: Is the problem deterministic promotion (one doc must win for one query) or organic ranking (several docs should score better)? Data needed: index name, mapping properties, current query JSON, example query strings, and target document ID(s) when pinning. -
Choose the relevance lever. Apply the decision from step 1:
-
Pinning / promotion → Create a query-rules ruleset with a rule of type(never
pinnedfor promotion). Setexcludeso the rule fires only for the intended query text — e.g.,criteriaorcontainson a metadata key such asexactwith valuequery_string. Set"sale"to pin the correct document viaactions(e.g.,ids) or["SKU123"](e.g.,docs). Use[{"_index":"catalog","_id":"SKU123"}]whendocsmay not be unique across indices. Read Query Rules Reference for full structure._id -
Organic ranking → Replace single-fieldon a long field with
matchacross the mappedmulti_matchfields. Boost short fields (typicallytextwithtitle^2unboosted). Considerdescription,operator, or synonym-aware analyzers when multi-word recall is still poor — but do not sort by price, date, or keyword fields to fake better text relevance, and do not queryminimum_should_matchsub-fields with.keywordfor analyzed user phrases. Read Multi-Match Tuning.term
Decision: Pick exactly one primary lever per request. Data needed: chosen fields and boosts, ruleset ID and rule ID names, criteria metadata keys, and pinned document identifiers. -
-
Apply the change. Execute the APIs for the chosen lever:Query rules path
- Create or replace the ruleset with (or add one rule with
PUT /_query_rules/{ruleset_id}).PUT /_query_rules/{ruleset_id}/_rule/{rule_id} - Confirm structure with .
GET /_query_rules/{ruleset_id} - Validate criteria with using the same
POST /_query_rules/{ruleset_id}/_testyou will pass at search time.match_criteria - Wire the search: must use a
POST /{index}/_searchquery whoserulereferences the ruleset and whoseruleset_idsupplies values for every criteriamatch_criteriakey (e.g.,metadata). Place the normal relevance clause inside"query_string": "sale". Creating the ruleset alone does not pin anything — the pin applies only when search includes theorganicquery.rule
Organic tuning path- Build a candidate (or equivalent bool/should) query from the mapping.
multi_match - Optionally inspect analysis with on sample query text when tokenization explains misses.
POST /{index}/_analyze
Decision: Stop after one coherent change set; avoid stacking unrelated edits before testing. - Create or replace the ruleset with
-
Test and compare top hits. Before and after each candidate, callwith the same
POST /{index}/_search(≥ 10), the user's query string, andsize. For pinning, the search body must include the"track_scores": truequery from step 3.ruleCompare for each run:- Top values and order
_id - where relevant
_score - Key fields (
_source,title, product id)description
For pinning, confirm the target document (e.g.,) is first whenSKU123matches the query and that organic matches still appear below. For organic tuning, confirm titles and intent-aligned documents rise without relying on sort or keyword exact-match hacks.match_criteriaDecision: Ship the candidate that wins on evidence; if none improve results, report what was tried and propose the next lever (e.g., synonyms or additional fields). Data needed: side-by-side top-hit lists from baseline and candidate queries. - Top
-
检查映射和当前查询。调用确认连接性。当索引未知时,使用
GET /缩小候选范围,然后调用GET /_cat/indices。GET /{index}/_mapping从映射中列出所有字段(例如text、title)以及所有用于过滤的description字段(keyword、brand)。注意哪些字段是短字段(精准),哪些是长字段(召回)。如果提供了用户当前的搜索体,读取并识别其查询的字段,以及是否已使用category、rule或单字段multi_match。match决策:问题是确定性提升(单个文档需在单个查询中获胜)还是自然排名优化(多个文档应获得更高评分)?所需数据:索引名称、映射属性、当前查询JSON、示例查询字符串,以及固定时的目标文档ID。 -
选择相关性调节手段。应用步骤1的决策:
-
固定/提升 → 创建带有类型规则的查询规则集(提升时绝不要使用
pinned)。设置exclude使规则仅针对预期查询文本触发——例如,对元数据键criteria使用query_string或contains匹配,值为exact。设置"sale"通过actions(例如ids)或["SKU123"](例如docs)固定正确的文档。当[{"_index":"catalog","_id":"SKU123"}]在多个索引中可能不唯一时使用_id。查阅查询规则参考获取完整结构。docs -
自然排名优化 → 将长字段上的单字段替换为在映射的
match字段上的text。为短字段设置权重(通常multi_match,title^2不设置权重)。当多词召回效果仍不佳时,考虑使用description、operator或支持同义词的分析器——但不要通过按价格、日期或关键字字段排序来伪造更好的文本相关性,也不要对经过分析的用户短语使用minimum_should_match查询term子字段。查阅Multi-Match调优。.keyword
决策:每个请求仅选择一种主要调节手段。所需数据:选定的字段和权重、规则集ID和规则ID名称、条件元数据键,以及固定文档的标识符。 -
-
应用更改。为所选调节手段执行API:查询规则路径
- 使用创建或替换规则集(或使用
PUT /_query_rules/{ruleset_id}添加单个规则)。PUT /_query_rules/{ruleset_id}/_rule/{rule_id} - 使用确认结构。
GET /_query_rules/{ruleset_id} - 使用验证条件,传入搜索时将使用的相同
POST /_query_rules/{ruleset_id}/_test。match_criteria - 关联搜索:必须使用
POST /{index}/_search查询,其rule引用规则集,ruleset_id为每个条件match_criteria键提供值(例如metadata)。将正常相关性子句放在"query_string": "sale"内部。仅创建规则集不会固定任何内容——只有当搜索包含organic查询时,固定效果才会生效。rule
自然调优路径- 根据映射构建候选(或等效的bool/should)查询。
multi_match - 当分词导致匹配失败时,可对示例查询文本调用检查分析结果。
POST /{index}/_analyze
决策:完成一套连贯的更改后停止;测试前避免堆叠无关编辑。 - 使用
-
测试并对比顶部结果。在每个候选方案前后,使用相同的(≥10)、用户的查询字符串和
size调用"track_scores": true。对于固定操作,搜索体必须包含步骤3中的POST /{index}/_search查询。rule每次运行对比以下内容:- 顶部值及其顺序
_id - 相关的
_score - 关键字段(
_source、title、产品ID)description
对于固定操作,确认当匹配查询时,目标文档(例如match_criteria)位于首位,自然匹配结果仍显示在下方。对于自然调优,确认标题和符合意图的文档排名提升,且不依赖排序或关键字精确匹配的技巧。SKU123决策:采用经证据验证有效的候选方案;如果没有方案提升结果,报告已尝试的内容并提出下一种调节手段(例如同义词或额外字段)。所需数据:基线查询和候选查询的并排顶部结果列表。 - 顶部
Examples
示例
Pin SKU123 for query "sale" on catalog
catalog在catalog
索引中针对查询"sale"固定SKU123
catalogWrong: Boost , sort by , or create a ruleset without a search query.
SKU123_idruleRight:
- with a
PUT /_query_rules/catalog-sale-pinrule, criteria matching query textpinned, actions pinning"sale".SKU123 - with:
POST /catalog/_search
json
{
"query": {
"rule": {
"ruleset_id": "catalog-sale-pin",
"match_criteria": { "query_string": "sale" },
"organic": {
"multi_match": {
"query": "sale",
"fields": ["title^2", "description"]
}
}
}
},
"size": 10
}Verify is hit #1 and remaining hits are organic matches below the pin.
SKU123错误做法:对设置权重、按排序,或创建规则集但不添加搜索查询。
SKU123_idrule正确做法:
- 调用,创建
PUT /_query_rules/catalog-sale-pin规则,条件匹配查询文本pinned,操作固定"sale"。SKU123 - 调用,请求体如下:
POST /catalog/_search
json
{
"query": {
"rule": {
"ruleset_id": "catalog-sale-pin",
"match_criteria": { "query_string": "sale" },
"organic": {
"multi_match": {
"query": "sale",
"fields": ["title^2", "description"]
}
}
}
},
"size": 10
}验证是第一个结果,其余结果是固定下方的自然匹配项。
SKU123Improve "running shoes" when only description
is searched
description仅搜索description
时优化"running shoes"的结果
descriptionMapping provides and as , plus and as .
titledescriptiontextbrandcategorykeywordWrong: Keep on only; sort by price; query on .
matchdescriptiontermtitle.keywordRight:
- Baseline: with the user's current
POST /catalog/_searchonmatch; record top hits.description - Candidate: with:
POST /catalog/_search
json
{
"query": {
"multi_match": {
"query": "running shoes",
"fields": ["title^2", "description"],
"type": "best_fields",
"operator": "or",
"minimum_should_match": "75%"
}
},
"size": 10
}- Compare top hits — documents with "running shoes" in should rank above description-only matches. If recall is still thin, consider synonym expansion in a follow-up iteration (not sort-by-price).
title
映射中和为字段,和为字段。
titledescriptiontextbrandcategorykeyword错误做法:仅保留上的查询;按价格排序;对使用查询。
descriptionmatchtitle.keywordterm正确做法:
- 基线:使用用户当前的上的
description查询调用match;记录顶部结果。POST /catalog/_search - 候选方案:调用,请求体如下:
POST /catalog/_search
json
{
"query": {
"multi_match": {
"query": "running shoes",
"fields": ["title^2", "description"],
"type": "best_fields",
"operator": "or",
"minimum_should_match": "75%"
}
},
"size": 10
}- 对比顶部结果——中包含"running shoes"的文档应排名仅
title包含该短语的文档之前。如果召回率仍低,可在后续迭代中考虑同义词扩展(而非按价格排序)。description
Guidelines
指南
- Ground every field name in the mapping — never invent ,
name, orcontentwithout checkingbody.GET /{index}/_mapping - Query rules for pins, boosts for ranking — merchandising belongs in query rules; field boosts belong in organic queries.
- Match criteria wiring is mandatory — keys in rule criteria must appear in the search
metadataobject with the runtime values (typically the user's query string).rule.match_criteria - Test before claiming success — run baseline and candidate searches; cite top-hit changes.
- Keyword fields filter; text fields search — use fields in
keywordcontext, not as the primary full-text target for natural language.filter - Always deliver the concrete artifact — even when you cannot connect to a cluster to verify, produce the full ruleset JSON (for pinning) or the candidate query body (for organic tuning), then explain how to verify once the connection is available. Never stop at a high-level outline.
- 所有字段名称均基于映射——未经检查,切勿自行创建
GET /{index}/_mapping、name或content字段。body - 固定结果用查询规则,排名优化用权重——商品推广属于查询规则的范畴;字段权重属于自然查询的范畴。
- 条件关联是必需的——规则条件中的键必须出现在搜索的
metadata对象中,并带有运行时值(通常为用户的查询字符串)。rule.match_criteria - 成功前必须测试——运行基线和候选查询;引用顶部结果的变化。
- 关键字字段用于过滤;文本字段用于搜索——在上下文中使用
filter字段,而非作为自然语言的主要全文搜索目标。keyword - 始终提供具体的工件——即使无法连接到集群进行验证,也要生成完整的规则集JSON(用于固定)或候选查询体(用于自然调优),然后说明连接可用后如何验证。切勿仅停留在高层概述。
References
参考
- Query Rules Reference — criteria types, actions, ruleset JSON,
pinnedquery wiring, test APIrule - Multi-Match Tuning — field boosts, operators, testing discipline, anti-patterns
- 查询规则参考——条件类型、操作、规则集JSON、
pinned查询关联、测试APIrule - Multi-Match调优——字段权重、运算符、测试规范、反模式
Operations
操作
| HTTP API (shorthand) | |
|---|---|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| HTTP API(简写) | |
|---|---|
| |
| |
| |
| |
| |
| |
| |
| |
| |