作者:来自 Elastic Kathleen_DeRusso
查询规则(Query rules)为用户提供了一种对特定查询进行细粒度控制的方法。目前,查询规则的功能允许你将你选择的搜索结果固定在结果集的顶部,和/或根据上下文查询数据从结果集中排除特定文档。
这种类型的查找调整控制有几种用例。其中包括将业务规则(例如促销活动)应用于你的搜索结果或 “修复” 高度可见的问题查询。
查询规则可以使用规则查询(rule query)访问,并且很快将作为与 RRF 等重新排名策略配合使用的检索器(retriever)提供!
这篇文章是关于如何知道你的查询规则是否按预期工作。
让我们从一个非常简单的示例开始,其中包含一个固定规则和一个排除规则:
`
1. PUT my-index/_doc/my-pinned-doc
2. {
3. "title": "My pinned document"
4. }
6. PUT my-index/_doc/my-excluded-doc
7. {
8. "title": "My excluded document"
9. }
12. PUT _query_rules/my-ruleset
13. {
14. "rules": [
15. {
16. "rule_id": "my-pinned-rule",
17. "type": "pinned",
18. "criteria": [
19. {
20. "type": "exact",
21. "metadata": "match",
22. "values": [
23. "pinned"
24. ]
25. }
26. ],
27. "actions": {
28. "ids": [
29. "my-pinned-doc"
30. ]
31. }
32. },
33. {
34. "rule_id": "my-exclude-rule",
35. "type": "exclude",
36. "criteria": [
37. {
38. "type": "exact",
39. "metadata": "match",
40. "values": [
41. "exclude"
42. ]
43. }
44. ],
45. "actions": {
46. "ids": [
47. "my-excluded-doc"
48. ]
49. }
50. }
51. ]
52. }
`代码解读
当查询规则启动时,我们仅支持 pinned 规则。此规则保证指定的文档出现在搜索结果的顶部,无论它们是否会在原始查询中返回。因此,验证规则是否应用的解决方法可能是发出 match_none 查询作为规则查询的 organic 部分,确保任何返回的文档都是由于规则匹配而固定的命中。
对于上述示例,这可能看起来像:
`
1. POST my-index/_search
2. {
3. "query": {
4. "rule": {
5. "organic": {
6. "match_none": {}
7. },
8. "ruleset_ids": [
9. "my-ruleset"
10. ],
11. "match_criteria": {
12. "match": "pinned"
13. }
14. }
15. }
16. }
`代码解读
此后,我们添加了 exclude 规则,用于识别结果集中永远不应返回的文档。
同样,对于 exclude 规则,你可以针对 ids 查询运行规则查询,或者针对非常小的数据集运行 match_all 查询:
`
1. POST my-index/_search
2. {
3. "query": {
4. "rule": {
5. "organic": {
6. "ids": {
7. "values": [
8. "my-excluded-doc"
9. ]
10. }
11. },
12. "ruleset_ids": [
13. "my-ruleset"
14. ],
15. "match_criteria": {
16. "match": "exclude"
17. }
18. }
19. }
20. }
`代码解读
这不是最好的解决方案,因此我们在 Elasticsearch 8.16 版中引入了一个新的查询规则测试器 API 调用(query rule tester API call),它允许你确定哪些规则符合特定条件,以及它们的应用顺序。以下是如何调用它的示例:
`
1. POST _query_rules/my-ruleset/_test
2. {
3. "match_criteria": {
4. "match": "exclude"
5. }
6. }
`代码解读
该调用将返回以下响应:
`
1. {
2. "total_matched_rules": 1,
3. "matched_rules": [
4. {
5. "ruleset_id": "my-ruleset",
6. "rule_id": "my-exclude-rule"
7. }
8. ]
9. }
`代码解读
这在未来也同样适用,即使添加了新的规则,这些规则不会从搜索结果中选择或排除文档。
祝你愉快地管理搜索结果!
原文:Dec 11th, 2024: [EN] Troubleshooting query rules - Advent Calendar - Discuss the Elastic Stack