Elasticsearch查詢時還在百度DSL語句嗎?你可能需要這份總結
- 2019 年 10 月 4 日
- 筆記
常用 es 查詢盤點
熟悉了關係型資料庫的結構概念以及查詢,再去使用屬於非關係型資料庫的 Elasticsearch 時,簡直是噩夢。第一道難關便是概念上的轉換。索引?類型?文檔?what?
下面是概念上的對應,大家可以類比了解
Relational DB -> Databases -> Tables -> Rows -> Columns Elasticsearch -> Indices -> Types -> Documents -> Fields
熟悉了各種概念後,下一道難關便是增刪改查,而最最常用的是查詢!如同 SQL 一樣,它有一套自己的查詢語句 - DSL 查詢。所以,下面為大家總結一下常用的查詢,然後你就可以像翻字典一樣,用時瞄兩眼了 ~ 嘿嘿,真他娘的是個天才 ...
1.基礎的不能再基礎查詢
查詢所有的索引及容量:
GET _cat/indices
GET 代表請求方式; _cat/indices 代表查詢部分。訪問的 url 寫全為:
localhost:9200/_cat/indices
查詢某一索引的映射結構:
GET 索引名/_mapping
查詢所有的相同前綴索引:(如以 yan 開頭)
GET yan*/_search
查詢所有索引模板:
GET _template
查詢具體索引模板:
GET _template/模板名
查詢集群健康狀態:
GET _cluster/health
查詢所有節點:
GET _cat/nodes
查詢索引及分片的分布:
GET _cat/shards
查詢所有插件:
GET _cat/plugins
2.有點難度的查詢
查詢某個索引的全部數據:
GET /index/type/_search { "query": { "match_all": {} } }當然你也可以直接寫 URL 查詢(默認返回 10 條文檔):
localhost:9200/索引名/_search?pretty
pretty參數是為了瀏覽器顯示的美觀一些。
根據某一欄位精確查詢:
GET /index/type/_search { "query": { "term": { "欄位名" : "值" } } }根據某一欄位模糊匹配:
GET /index/type/_search { "query": { "match": { "欄位名" : "值" } } }根據某一欄位值進行範圍查找:
GET /index/type/_search { "query": { "range": { # 欄位名: 條件 "age":{ "gte" : 15 , "lte" : 25 } } } }gte 是大於等於;lte 是小於等於
根據條件進行過濾查詢:
GET /index/type/_search { "query": { "bool": { "filter": { "term":{"欄位":"值"} } } } }多條件"或"關係:
GET /index/type/_search { "query": { "bool": { "should": [{ "term": { "欄位": "值" } }, { "match": { "欄位": "值" } }] } } }多條件"與"關係:
GET /index/type/_search { "query": { "bool": { "must" : [{ "match" : { "name" : "Ethanyan" } },{ "range":{ "age":{ "from" : 18 , "to" : 26 } } }] } } }嚴格匹配:
GET /index/type/_search { "query": { "bool": { "must" : { "range" : { "age" : { "from" : 18, "to" : 26 } } } } } }嚴格不匹配:
GET /index/type/_search { "query": { "bool": { "must_not" : { "term" : { "name" : "Ethanyan" } } } } }複合查詢:
GET /index/type/_search { "query": { "bool": { "should": [{ "match": { "age": 18 } }, { "match": { "age": 26 } } ], "filter": { "match": { "name": "Ethanyan" } } } } }3.注意事項
1.索引、模板之類的名稱不能出現字母大寫。
2.在查詢時,要寫 DSL 語句,所以需要攜帶請求體,那麼為什麼還是 get 請求?
