詳解如何在Elasticsearch中搜索空值
引言
根據(jù) Elasticsearch 文檔,無法索引或搜索空值 null。 當(dāng)一個字段設(shè)置為 null(或空數(shù)組或空值數(shù)組)時,它被視為該字段沒有值。
那么如何找到 product_name 為空(null)的文件呢?
選項 1:null_value 映射參數(shù)
你可以在配置索引映射時定義 null_value 參數(shù)。 它將允許你在索引文檔時用指定值替換顯式空值 null,以便它可以被索引和搜索。
讓我們創(chuàng)建索引名稱 products,其中包含值為 NULL 的 product_name 字段。
PUT products { "mappings": { "properties": { "product_name":{ "type": "keyword", "null_value": "NULL" } } } }
讓我們用 product_name 字段索引一些文檔,該字段的值為 null 或空數(shù)組。
POST products/_doc/1 { "product_name": null, "company":"apple" } POST products/_doc/2 { "product_name": [], "company":"apple" }
讓我們查詢并檢查我們得到的結(jié)果:
POST products/_search { "query": { "match": { "product_name": "NULL" } } }
上面的搜索結(jié)果為:
` { "took": 1009, "timed_out": false, "_shards": { "total": 1, "successful": 1, "skipped": 0, "failed": 0 }, "hits": { "total": { "value": 1, "relation": "eq" }, "max_score": 0.2876821, "hits": [ { "_index": "products", "_id": "1", "_score": 0.2876821, "_source": { "product_name": null, "company": "apple" } } ] } } `
什么??? 為什么 Elasticsearch 只返回一個文檔而不返回第二個具有空數(shù)組的文檔? 因為,
- 一個空數(shù)組不包含明確的 null,因此不會被 null_value 替換。
此外,product_name 值僅作為 null 而不是作為在索引映射中設(shè)置的 NULL。 因為,
- null_value 只影響數(shù)據(jù)的索引方式,它不會修改 _source 文檔。
現(xiàn)在,當(dāng) product_name 為 null 或空數(shù)組時,如何將兩個文檔都放入結(jié)果中?
選項2:使用 MUST_NOT 查詢
讓我們定義沒有 null_value 的索引映射和與上面相同的索引文檔。
PUT products { "mappings": { "properties": { "product_name":{ "type": "keyword" } } } }
現(xiàn)在你可以使用以下查詢:
POST products/_search { "query": { "bool": { "must_not": [ { "exists": { "field": "product_name" } } ] } } }
上述查詢的結(jié)果,它現(xiàn)在返回兩個結(jié)果:
` { "took": 1, "timed_out": false, "_shards": { "total": 1, "successful": 1, "skipped": 0, "failed": 0 }, "hits": { "total": { "value": 2, "relation": "eq" }, "max_score": 0, "hits": [ { "_index": "products", "_id": "1", "_score": 0, "_source": { "product_name": null, "company": "apple" } }, { "_index": "products", "_id": "2", "_score": 0, "_source": { "product_name": [], "company": "apple" } } ] } } `
將 must_not 與 exists 查詢一起使用的優(yōu)點:
- 此選項 2 不依賴于字段的數(shù)據(jù)類型,無論字段的數(shù)據(jù)類型如何,它都會起作用,但選項 1 null_value 需要與字段的數(shù)據(jù)類型相同。 例如,長字段不能有字符串 null_value。
- 選項 1 不適用于文本類型的字段,因為 Elasticsearch 不允許為文本類型的字段設(shè)置 null_value 參數(shù)。
- 選項 2 也是單一且高效的解決方案,因為 1) 它不需要根據(jù)字段映射中定義的值添加 null 值的開銷。2)索引大小也會變小,導(dǎo)致索引變少,搜索查詢變快。
以上就是詳解如何在Elasticsearch中搜索空值的詳細(xì)內(nèi)容,更多關(guān)于Elasticsearch搜索空值的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
詳解Spring Boot實戰(zhàn)之Rest接口開發(fā)及數(shù)據(jù)庫基本操作
本篇文章主要介紹了Spring Boot實戰(zhàn)之Rest接口開發(fā)及數(shù)據(jù)庫基本操作,具有一定的參考價值,有興趣的可以了解一下2017-07-07Springboot整合Flowable6.x導(dǎo)出bpmn20的步驟詳解
這篇文章主要介紹了Springboot整合Flowable6.x導(dǎo)出bpmn20,Flowable流程引擎可用于部署B(yǎng)PMN 2.0流程定義,可以十分靈活地加入你的應(yīng)用/服務(wù)/構(gòu)架,本文給出兩種從flowable導(dǎo)出流程定義bpmn20.xml的方式,需要的朋友可以參考下2023-04-04springboot 設(shè)置server.port不生效的原因及解決
這篇文章主要介紹了springboot 設(shè)置server.port不生效的原因及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08