我有一個索引,我需要將兩個欄位的乘法過濾到一個范圍內。
首先,這是我的“專案”索引的映射:
{
"mappings": {
"properties": {
"name": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"price": {
"type": "float"
},
"discount": {
"type": "float"
}
}
}
}
一件商品的實際價格是其價格乘以折扣。
我需要為實際價格介于兩個數字之間的商品創建查詢:X <= price * discount <= Y
我查看了 Elasticsearch 的檔案,但是范圍查詢似乎只考慮了單個欄位的值,而不是兩個欄位的乘積:
{
"query": {
"range": {
"price": { // only price
"gte": 10, // X
"lte": 200, // Y
}
}
}
}
我想知道除了添加另一個欄位來存盤要在查詢中使用的相乘值之外是否還有其他解決方案。
謝謝你。
uj5u.com熱心網友回復:
您有 2 個選擇:
- 在索引時間添加欄位
- 使用運行時欄位
1是不言自明的,它在大多數情況下是推薦的,因為存盤比計算便宜。如果你不存盤它,你將不得不每次都計算它。
- 您可以使用運行時欄位在映射或查詢中生成這個新欄位。
我會告訴你兩種方式:
映射
PUT test_product
{
"mappings": {
"runtime": {
"discount_price": {
"type": "double",
"script": {
"source": "emit(doc['price'].value * doc['discount'].value )"
}
}
},
"properties": {
"name": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"price": {
"type": "double"
},
"discount": {
"type": "double"
}
}
}
}
攝取檔案
POST test_product/_doc
{
"name": "Orange",
"price": "10.0",
"discount": "0.5"
}
運行查詢:
GET test_product/_search
{
"query": {
"range": {
"discount_price": {
"gte": 5,
"lte": 5
}
}
}
}
現在無需在映射中定義運行時欄位:
GET test_product/_search
{
"runtime_mappings": {
"discount_price": {
"type": "double",
"script": {
"source": "emit(doc['price'].value * doc['discount'].value )"
}
}
},
"query": {
"range": {
"discount_price": {
"gte": 5,
"lte": 5
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/537901.html
標籤:弹性搜索搜索过滤乘法elasticsearch-dsl
上一篇:搜索模板中的小胡子雙引號問題
