elasticsearch定義了兩種查詢方式:
一、索引(index)、type、document 相關語句
1、列出所有索引的狀態 GET /_cat/indices?v
health status index uuid pri rep docs.count docs.deleted store.size pri.store.size yellow open my_index SOgui_yKSXacTlMHQQht9w 5 1 5 0 14.3kb 14.3kb yellow open bank tzxmtSQhQsqWFfzVjmaK_A 5 1 1008 1 504.9kb 504.9kb yellow open schools SG4nAwtJTcOXCcnf7-mq8w 5 1 0 0 1.2kb 1.2kb yellow open teacher od83pADqTGSk4_TzfGP1ww 5 1 3 0 10.8kb 10.8kb yellow open student oTQ3KElZRzKb3UphMQV41w 5 1 0 0 1.2kb 1.2kb yellow open my_store 1e57BmarQ-OQWr5EZFXu5A 5 1 4 0 11.9kb 11.9kb
2、查詢索引詳細信息
GET /index1,index2 查詢索引index1和索引index2的基本信息 GET /_all 查詢所有的基本信息 GET /s* 使用通配符來查詢所有以s開頭的索引信息
3、創建索引 (新版本一個index只能有一個type)
setting中可以設置索引的主分片數number_of_shards默認為5,和主分片的副本數number_of_replicas默認是1;
mapping中主要設置各個type的映射關系。
PUT /my_index { "settings": { ... any settings ... }, "mappings": { "type_one": { ... any mappings ... }, "type_two": { ... any mappings ... }, ... } }
...
PUT /index1 { "mappings": { "tweet" : { "properties" : { "tweet" : { "type" : "text", "analyzer": "english" }, "date" : { "type" : "date" }, "name" : { "type" : "text" }, "user_id" : { "type" : "long" } } } } }
4、刪除索引
DELETE /{index} DELETE /_all DELETE /*
5、在索引的映射中增加一個字段的映射
PUT /gb/_mapping/tweet { "properties" : { "tag" : { "type" : "text", "index": "false" } } }
6、查看某個type的映射關系 GET /{index}/_mapping/{type}
GET /gb/_mapping/tweet ///返回 { "gb": { "mappings": { "tweet": { "properties": { "date": { "type": "date" }, "name": { "type": "text" }, "tag": { "type": "text", "index": false }, "tweet": { "type": "text", "analyzer": "english" }, "user_id": { "type": "long" } } } } } }
7、在索引文檔中添加或者替換文檔,在添加的時候id並不是必須的,如果沒有設置id,則會隨機產生一個id
PUT /{index}/{type}/{id} { "filed":"value" }
8、更新索引中文檔的內容
POST /{index}/{type}/{id}/_update { "doc":{ "name":"kyle", "age":20 } }
9、刪除文檔 DELETE /{index}/{type}/{id}
10、批處理
POST /teacher/chinese/_bulk {"index":{"_id":"3"}} {"name": "John Doe" } {"index":{"_id":"4"}} {"name": "Jane Doe" } POST /teacher/chinese/_bulk {"update":{"_id":"1"}} {"doc": { "name": "jimmy" } } {"delete":{"_id":"2"}} POST /_bulk { "delete": { "_index": "website", "_type": "blog", "_id": "123" }} { "create": { "_index": "website", "_type": "blog", "_id": "123" }} { "title": "My first blog post" } { "index": { "_index": "website", "_type": "blog" }} { "title": "My second blog post" } { "update": { "_index": "website", "_type": "blog", "_id": "123", "_retry_on_conflict" : 3} } { "doc" : {"title" : "My updated blog post"} }
11、批量導入大量數據(注意文本的最后要空一行) curl -H "Content-Type: application/json" -XPOST "localhost:9200/bank/account/_bulk?pretty&refresh" --data-binary "@accounts.json"
{"index":{"_id":"1"}} {"account_number":1,"balance":39225,"firstname":"Amber","lastname":"Duke","age":32,"gender":"M","address":"880 Holmes Lane", "employer":"Pyrami","email":"amberduke@pyrami.com","city":"Brogan","state":"IL"} {"index":{"_id":"2"}} {"account_number":6,"balance":5686,"firstname":"Hattie","lastname":"Bond","age":36,"gender":"M","address":"671 Bristol Street", "employer":"Netagy","email":"hattiebond@netagy.com","city":"Dante","state":"TN"}
12、查詢文檔數
GET /_count ///查詢所有文檔數 GET /index/_count ///查詢index中文檔數 GET /index/type/_count ///查詢type中的文檔
13、創建新的文檔而不是覆蓋有兩種做法,創建成功會返回
PUT /website/blog/123?op_type=create { ... } PUT /website/blog/123/_create { ... }
14、使用腳本對文檔進行更新,在原有的基礎上加1,upsert表示如果沒有該字段就初始化為1,retry_on_conflict=5表示更新失敗后還要重試5次,因為有些操作是不在意執行的先后順序的
POST /bank/account/1/_update?retry_on_conflict=5 { "script" : "ctx._source.balance+=1", "upsert": { "balance": 1 } }
二、簡單查詢:使用GET請求在URL后面攜帶參數來進行簡單的查詢
1、GET /bank/account/_search?_source=account_number,balance,&size=1&from=0&q=account_number:44
//這是查詢返回的結果 { "took": 2, //執行整個搜索請求耗費了多少毫秒 "timed_out": false, //查詢是否超時 "_shards": { //表示查詢中參與分片的總數,以及這些分片成功了多少個失敗了多少個 "total": 5, "successful": 5, "skipped": 0, "failed": 0 }, "hits": { //所有查詢到的結果 "total": 1008, //表示匹配到的文檔總數 "max_score": 1, //結果中最大的評分 "hits": [ { "_index": "bank", // 索引名稱 "_type": "account", //type名稱 "_id": "25", //id名稱 "_score": 1, //評分 "_source": { //存儲的數據源信息 "account_number": 25, "balance": 40540, "firstname": "Virginia", "lastname": "Ayala", "age": 39, "gender": "F", "address": "171 Putnam Avenue", "employer": "Filodyne", "email": "virginiaayala@filodyne.com", "city": "Nicholson", "state": "PA" } } ] } }
2、同時查詢多索引多類型的數據
/_search在所有的索引中搜索所有的類型 /gb/_search在 gb 索引中搜索所有的類型 /gb,us/_search在 gb 和 us 索引中搜索所有的文檔 /g*,u*/_search在任何以 g 或者 u 開頭的索引中搜索所有的類型 /gb/user/_search在 gb 索引中搜索 user 類型 /gb,us/user,tweet/_search在 gb 和 us 索引中搜索 user 和 tweet 類型 /_all/user,tweet/_search在所有的索引中搜索 user 和 tweet 類型
3、不查詢文檔的元數據,只查詢source部分的數據 GET /{index}/{type}/{id}/_source
GET /bank/account/44/_source //返回 { "account_number": 44, "balance": 34487, "firstname": "Aurelia", "lastname": "Harding", "age": 37, "gender": "M", "address": "502 Baycliff Terrace", "employer": "Orbalix", "email": "aureliaharding@orbalix.com", "city": "Yardville", "state": "DE" }
三、請求體查詢:使用HTTP請求來發送json數據進行查詢
1、查詢所有的文檔,默認評分是1,可以通過設置boost來,由於有些代理服務器不支持GET請求帶請求體,所以實際中還是要用POST請求。
GET /bank/account/_search { "query": { "match_all": {"boost":1.2} } }
2、分頁查詢所有文檔
GET /bank/account/_search { "query": { "match_all": {} }, "from": 0, "size": 1 }
3、查詢gender為M的賬戶,只顯示account_number,gender,balance三個字段,通過balance倒序排列,從第一條開始查,頁大小為20
GET /bank/account/_search { "query":{ "match": { "gender":"M" } }, "_source":[ "account_number", "gender", "balance" ], "sort": [ { "balance": "desc" } ], "from":0, "size":20 }
4、全文檢索,索引中只要有任意一個匹配拆分后詞就可以出現在結果中,只是匹配度越高的排越前面
GET /bank/account/_search { "query":{ "match": { "address":"street" } } }
上面的操作是默認為or,可以設置operator為and,這樣就必須要所有的詞都要匹配
GET /bank/account/_search { "query":{ "match": { "address":{ "query":"171 Putnam", "operator":"and" } } } }
5、短語搜索,查詢首先將查詢字符串解析成一個詞項列表,然后對這些詞項進行搜索,但只保留那些包含 全部 搜索詞項,且 位置 與搜索詞項相同的文檔。就相當於拿查詢字符串直接去文檔里面找
GET /_search { "query": { "match_phrase" : { "message" : "this is a test" } } }
6、match_phrase_prefix和match_phrase一樣,不過它可以允許文本的最后一項使用前綴匹配。
GET /_search { "query": { "match_phrase_prefix" : { "message" : { "query" : "quick brown f", "max_expansions" : 10 } } } }
7、可以匹配多字段,如下可以使用*還作為通配符進行匹配,使用^符號來對匹配字段的權重進行增加^3就是權重增加三倍。
GET /_search
{
"query": { "multi_match" : { "query": "this is a test", "fields": [ "subject^3", "message*" ] } } }
8、短語匹配,但是允許中間間隔幾個詞,slop為幾就是允許間隔幾個詞,幾個詞之間離的越近分數越高
GET /bank/account/_search
{
"query":{ "match_phrase": { "address":{ "query":"171 Avenue", "slop":"1" } } } }
9、取回多個文檔
///不同的index、不同的type
GET /_mget
{
"docs" : [ { "_index" : "index1", "_type" : "type1", "_id" : 2 }, { "_index" : "index2", "_type" : "type2", "_id" : 1, "_source":[ "filed1", "filed2" ] } ] }
..
///相同的index,不同的type
GET /{index}/_mget
{
"docs" : [ {"_type":"type1","_id" : 2}, {"_type":"type2", "_id" :1 } ] }
...
///相同的index和type,不同的id
GET /{index}/{type}/_mget
{
"ids":[1,2] }
10、term查找被用於精確值 匹配,這些精確值可能是數字、時間、布爾或者那些 not_analyzed
的字符串。term
查詢對於輸入的文本不 分析 ,所以它將給定的值進行精確查詢。
注意:如果要用term查找某個字段的值,要避免這個字段沒有被分詞,否則可能無法匹配到
GET /bank/account/_search
{
"query":{ "term": { "address": "171" } } }
11、terms查詢和 term
查詢一樣,但它允許你指定多值進行匹配。如果這個字段包含了指定值中的任何一個值,那么這個文檔滿足條件。terms 查詢對於輸入的文本不分析。它查詢那些精確匹配的值(包括在大小寫、重音、空格等方面的差異)。
GET /bank/account/_search
{
"query":{ "terms": { "address": [ "Banker", "171", "Street"] } } }
12、exists和missing查詢,分別用來判斷是否存在或者缺失。
///查詢是否存在field_name這個字段
GET /my_index/posts/_search
{
"query" : { "constant_score" : { "filter" : { "exists" : { "field" : "field_name" } } } } }
13、組合查詢,因為很多時候查詢條件都比較復雜,這時就需要使用bool來將多個查詢組合起來。bool接收一下參數
must
文檔 必須 匹配這些條件才能被包含進來。
must_not
文檔 必須不 匹配這些條件才能被包含進來。
should
如果滿足這些語句中的任意語句,將增加 _score
,否則,無任何影響。它們主要用於修正每個文檔的相關性得分。
filter
必須 匹配,但它以不評分、過濾模式來進行。這些語句對評分沒有貢獻,只是根據過濾標准來排除或包含文檔。filter中也可以嵌套bool
GET /bank/account/_search
{
"query": { "bool": { "must":{ "match": { "address": "street" } }, "must_not": { "match": { "balance": "47406" } }, "should": [ { "match": { "balance": "3150" }} ], "filter": { "range": { "age": { "gte":30 } } } } } }
...
//bool過濾器可以嵌套使用
GET /my_store/products/_search
{
"query" : { "filtered" : { "filter" : { "bool" : { "should" : [ { "term" : {"productID" : "KDKE-B-9947-#kL5"}}, { "bool" : { "must" : [ { "term" : {"productID" : "JODL-X-1937-#pV7"}}, { "term" : {"price" : 30}} ] }} ] } } } } }
14、constant_score查詢:它被經常用於你只需要執行一個 filter 而沒有其它查詢(例如,評分查詢)的情況下。可以使用它來取代只有 filter 語句的 bool
查詢。在性能上是完全相同的,但對於提高查詢簡潔性和清晰度有很大幫助。
GET /bank/account/_search
{
"query": { "constant_score": { "filter": { "term": { "age": 30 } } } } }
15、驗證查詢:驗證查詢語句是否正確。
GET /bank/account/_validate/query
{
"query": { "constant_score": { "filter": { "term": { "age": 30 } } } } }
16、確保查詢的字段與輸入的字段完全匹配,最好的方式是增加並索引另一個字段, 這個字段用以存儲該字段包含詞項的數量。
GET /my_index/my_type/_search
{
"query": { "constant_score" : { "filter" : { "bool" : { "must" : [ { "term" : { "tags" : "search" } }, { "term" : { "tag_count" : 1 } } ] } } } } }
17、范圍查找range,如果對字符串進行比較,那么是數字<大寫字母<小寫字母,字符從頭開始比較,和js一樣。
range的主要參數為:
gt
: >
大於(greater than)
lt
: <
小於(less than)
gte
: >=
大於或等於(greater than or equal to)
lte
: <=
小於或等於(less than or equal to)
GET /my_store/products/_search
{
"query" : { "constant_score" : { "filter" : { "range" : { "price" : { "gte" : 20, "lt" : 40 } } } } } }
..
///對於時間方面的范圍可以通過now來表示當前時間,下面表示最近一個小時之內
"range" : {
"timestamp" : { "gt" : "now-1h" } } ///可以通拿過||符號后面跟一個日期表達式來表示日期,下面表示小於2014-01-01 "range" : { "timestamp" : { "gt" : "2014-01-01 00:00:00", "lt" : "2014-01-01 00:00:00||+1M" } }
18、設置最小匹配度 后面可以是數字也可以是百分比
GET /my_index/my_type/_search
{
"query": { "match": { "title": { "query": "quick brown dog", "minimum_should_match": "75%" } } } }
19、通過boost來提升權限,boost默認值為1
GET /_search
{
"query": { "bool": { "must": { "match": { "content": { "query": "full text search", "operator": "and" } } }, "should": [ { "match": { "content": { "query": "Elasticsearch", "boost": 3 } }}, { "match": { "content": { "query": "Lucene", "boost": 2 } }} ] } } }
20、dis_max最大化查詢:將任何與任一查詢匹配的文檔作為結果返回,但只將最佳匹配的評分作為查詢的評分結果返回 。如果某一個field中匹配到了盡可能多的關鍵詞,那么就應被排在前面;而不是盡可能多的field匹配到了少數的關鍵詞排在前面。
{
"query": { "dis_max": { "queries": [ { "match": { "title": "Brown fox" }}, { "match": { "body": "Brown fox" }} ] } } }
21、tie_breaker
:上面的dis_max只是將最佳匹配分數作為分數有時並不合理,所以用tie_breaker來設置其他匹配分數的權重,那么最后的分數就是所有分數的總和,tie_breaker的值為0到1。
{
"query": { "dis_max": { "queries": [ { "match": { "title": "Quick pets" }}, { "match": { "body": "Quick pets" }} ], "tie_breaker": 0.3 } } }
22、使用multi_match查詢,多匹配查詢的類型有多種,其中的三種恰巧與 三個場景對應,即: best_fields
、 most_fields
和 cross_fields
(最佳字段、多數字段、跨字段)。我們可以使用multi_match來對查詢語句進行簡化。multi_match中盡量避免使用no_analyzed字段。
///原始查詢
{
"dis_max": { "queries": [ { "match": { "title": { "query": "Quick brown fox", "minimum_should_match": "30%" } } }, { "match": { "body": { "query": "Quick brown fox", "minimum_should_match": "30%" } } }, ], "tie_breaker": 0.3 } } ///簡化后的查詢 { "multi_match": { "query": "Quick brown fox", "type": "best_fields", "fields": [ "title", "body" ], "tie_breaker": 0.3, "minimum_should_match": "30%" } }
23、多數字段查詢most_field,根據字面上可知匹配的時候要盡可能將匹配了更多字段的文檔返回過來,所有的字段都參與評分。
GET /my_index/_search
{
"query": { "multi_match": { "query": "jumping rabbits", "type": "most_fields", "fields": [ "title^10", "title.std" ] } } }
24、cross_field跨字段查詢,將所有的字段看作是一個大的字段,然后去查詢。
GET /books/_search
{
"query": { "multi_match": { "query": "peter smith", "type": "cross_fields", "fields": [ "title^2", "description" ] } } }
25、使用臨近度提高相關度
GET /my_index/my_type/_search
{
"query": { "bool": { "must": { "match": { "title": { "query": "quick brown fox", "minimum_should_match": "30%" } } }, "should": { "match_phrase": { "title": { "query": "quick brown fox", "slop": 50 } } } } } }
26、prefix前綴查詢:默認狀態下, prefix
查詢不做相關度評分計算,它只是將所有匹配的文檔返回,並為每條結果賦予評分值 1
。
GET /my_index/address/_search
{
"query": { "prefix": { "postcode": "W1" } } }
27、通配符查詢wildcard:允許指定匹配的正則式。它使用標准的 shell 通配符查詢: ?
匹配任意字符, *
匹配 0 或多個字符。
GET /my_index/address/_search
{
"query": { "wildcard": { "postcode": "W?F*HW" } } }
28、正則表達式查詢Regexp:
GET /my_index/address/_search
{
"query": { "regexp": { "postcode": "W[0-9].+" } } }
29、查詢時輸入即搜索match_phrase_prefix,就是在原有match_phrase的基礎上將查詢字符串的最后一個詞作為前綴使用,來進行模糊匹配。
///參數 max_expansions 控制着可以與前綴匹配的詞的數量,它會先查找第一個與前綴 bl 匹配的詞,然后依次查找搜集與之匹配的詞(按字母順序),直到沒有更多可匹配的詞或當數量超過 max_expansions 時結束。
{
"match_phrase_prefix" : { "brand" : { "query": "walker johnnie bl", "slop": 10, "max_expansions":50 } } }