脚本查询
使用 script
查询根据 Painless 脚本语言编写的自定义条件筛选文档。此查询返回脚本评估结果为 true
的文档,从而启用无法使用标准查询表达的高级筛选逻辑。
script
查询的计算成本很高,应谨慎使用。仅在必要时使用,并确保 search.allow_expensive_queries
已启用(默认为 true
)。有关更多信息,请参阅高成本查询。
示例
创建名为 products
的索引,并使用以下映射
PUT /products
{
"mappings": {
"properties": {
"title": { "type": "text" },
"price": { "type": "float" },
"rating": { "type": "float" }
}
}
}
使用以下请求索引示例文档
POST /products/_bulk
{ "index": { "_id": 1 } }
{ "title": "Wireless Earbuds", "price": 99.99, "rating": 4.5 }
{ "index": { "_id": 2 } }
{ "title": "Bluetooth Speaker", "price": 79.99, "rating": 4.8 }
{ "index": { "_id": 3 } }
{ "title": "Noise Cancelling Headphones", "price": 199.99, "rating": 4.7 }
基本脚本查询
返回评分高于 4.6
的产品
POST /products/_search
{
"query": {
"script": {
"script": {
"source": "doc['rating'].value > 4.6"
}
}
}
}
返回的匹配项仅包含 rating
高于 4.6
的文档
{
...
"hits": {
"total": {
"value": 2,
"relation": "eq"
},
"max_score": 1,
"hits": [
{
"_index": "products",
"_id": "2",
"_score": 1,
"_source": {
"title": "Bluetooth Speaker",
"price": 79.99,
"rating": 4.8
}
},
{
"_index": "products",
"_id": "3",
"_score": 1,
"_source": {
"title": "Noise Cancelling Headphones",
"price": 199.99,
"rating": 4.7
}
}
]
}
}
参数
script
查询接受以下顶层参数。
参数 | 必需/可选 | 描述 |
---|---|---|
script.source | 必需 | 评估结果为 true 或 false 的脚本代码。 |
script.params | 可选 | 脚本中引用的用户定义参数。 |
使用脚本参数
您可以使用 params
安全地注入值,从而利用脚本编译缓存
POST /products/_search
{
"query": {
"script": {
"script": {
"source": "doc['price'].value < params.max_price",
"params": {
"max_price": 100
}
}
}
}
}
返回的匹配项仅包含 price
小于 100
的文档
{
...
"hits": {
"total": {
"value": 2,
"relation": "eq"
},
"max_score": 1,
"hits": [
{
"_index": "products",
"_id": "1",
"_score": 1,
"_source": {
"title": "Wireless Earbuds",
"price": 99.99,
"rating": 4.5
}
},
{
"_index": "products",
"_id": "2",
"_score": 1,
"_source": {
"title": "Bluetooth Speaker",
"price": 79.99,
"rating": 4.8
}
}
]
}
}
组合多个条件
使用以下查询来搜索 rating
高于 4.5
且 price
低于 100
的产品
POST /products/_search
{
"query": {
"script": {
"script": {
"source": "doc['rating'].value > 4.5 && doc['price'].value < 100"
}
}
}
}
只返回符合要求的文档
{
"took": 12,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 1,
"relation": "eq"
},
"max_score": 1,
"hits": [
{
"_index": "products",
"_id": "2",
"_score": 1,
"_source": {
"title": "Bluetooth Speaker",
"price": 79.99,
"rating": 4.8
}
}
]
}
}