gpt4 book ai didi

PHP Elastic Search 过滤查询字符串搜索

转载 作者:可可西里 更新时间:2023-11-01 00:30:02 25 4
gpt4 key购买 nike

所有人都希望使用过滤查询,其中结果应包含来自“query_string”以及应用的“term - filter”的数据。

GET blog/_search
{
"query": {
"filtered": {
"query": {
"query_string": {
"fields": [ "description" ],
"query": "a" // or just ""
}
},
"filter": {
"terms": {
"topic_id": [
10
]
}
}
}
}
}

预期的结果是:

  1. 所有包含字母“a”或“”且topic_id为10的博客记录。
  2. 还有 topic_id 为 10 的其余记录,即使描述为空白/空也是如此。

所以最终结果应该是 - 得分较高的匹配记录应该排在最前面,然后是与过滤器中的“topic_id”匹配的记录。

最佳答案

实现此目的的一种方法是使用 muti_fields description 字段的映射。多字段中的一个字段应该是非分析的。重新索引数据后,您可以使用简单的 bool query实现你想要的:

例子

创建索引:

put test
{
"mappings": {
"data" : {
"properties": {
"description" : {
"type": "string",
"fields": {
"raw" : {"type": "string","index": "not_analyzed"}
}
}
}
}
}
}

索引数据:

put test/data/1 
{
"description" : "a",
"test_id" : 10
}
put test/data/2
{
"description" : "",
"test_id" : 10
}

put test/data/3
{
"description" : "hello",
"test_id" : 10
}


put test/data/4
{
"description": "a",
"test_id" : 20
}

查询:

post test/data/_search
{
"query": {
"filtered": {
"query": {
"bool": {
"disable_coord": "true",
"should": [
{
"query_string": {
"fields": [
"description"
],
"query": "a"
}
},
{
"constant_score": {
"filter": {
"term": {
"description.raw": ""
}
},
"boost": 0.2
}
},
{
"constant_score": {
"filter": {
"exists": {
"field": "description"
}
},
"boost": 0.1
}
}
]
}
},
"filter": {
"terms": {
"test_id": [
10
]
}
}
}
}
}

结果:

 "hits": [
{
"_index": "test",
"_type": "data",
"_id": "1",
"_score": 0.5113713,
"_source": {
"description": "a",
"test_id": 10
}
},
{
"_index": "test",
"_type": "data",
"_id": "2",
"_score": 0.29277003,
"_source": {
"description": "",
"test_id": 10
}
},
{
"_index": "test",
"_type": "data",
"_id": "3",
"_score": 0.097590014,
"_source": {
"description": "hello",
"test_id": 10
}
}
]

查询空字符串:

{
"query": {
"filtered": {
"query": {
"bool": {
"disable_coord": "true",
"should": [
{
"query_string": {
"fields": [
"description"
],
"query": ""
}
},
{
"constant_score": {
"filter": {
"term": {
"description.raw": ""
}
},
"boost": 0.2
}
},
{
"constant_score": {
"filter": {
"exists": {
"field": "description"
}
},
"boost": 0.1
}
}
]
}
},
"filter": {
"terms": {
"test_id": [
10
]
}
}
}
}
}

结果:

  "hits": [
{
"_index": "test",
"_type": "data",
"_id": "2",
"_score": 1.3416407,
"_source": {
"description": "",
"test_id": 10
}
},
{
"_index": "test",
"_type": "data",
"_id": "1",
"_score": 0.44721356,
"_source": {
"description": "a",
"test_id": 10
}
},
{
"_index": "test",
"_type": "data",
"_id": "3",
"_score": 0.44721356,
"_source": {
"description": "hello",
"test_id": 10
}
}
]

关于PHP Elastic Search 过滤查询字符串搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37808547/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com