在系列的第一篇文章中咱們介紹了ElasticSearch的基本概念和操做,本文將繼續介紹ElasticSearch查詢和索引功能。html
目錄:git
結構化搜索將查詢條件以json的形式包含在http請求的body中,一般狀況下搜索請求應該使用GET方法但不是全部的客戶端和服務端都支持GET請求包含body。 所以,ElasticSearch支持使用GET或POST進行搜索。github
本節示例均使用默認analysis
和mapping
配置, 此狀態下ElasticSearch與普通的文檔數據庫幾乎無異。咱們將在下一節中介紹如何進行模糊查詢,使它成爲真正的搜索引擎。算法
精確查詢一般起到過濾的做用,由於不使用分析器解析一般很是迅速。sql
查詢可使用from和size參數對結果進行分頁:數據庫
{ "from": 0, "size": 10, "query": { "term": { "nickname": "easy" } } }
term查詢用於進行精確匹配:json
POST /blog/user/_search { "query": { "term": { "nickname": "easy" } } } response: { "took": 23, "timed_out": false, "_shards": { "total": 5, "successful": 5, "failed": 0 }, "hits": { "total": 2, "max_score": 0.45532417, "hits": [ { "_index": "blog", "_type": "user", "_id": "1", "_score": 0.45532417, "_source": { "nickname": "easy", "username": "user1", "status": "normal" } }, { "_index": "blog", "_type": "user", "_id": "2", "_score": 0.43648314, "_source": { "nickname": "easy", "username": "user2" "status": "normal" } } ] } }
在響應的hits.hits
字段中咱們能夠看到匹配的文檔,文檔_score
字段是採用TF-IDF算法得出匹配程度得分,結果集中的文檔按照得分降序排列。緩存
上述查詢能夠用sql表示爲:app
SELECT * FROM user WHERE nickname = "easy";
terms查詢能夠視爲多個term查詢的組合:less
POST /blog/user/_search { "query": { "terms": { "nickname": ["easy", "ease"] } } } response: { "took": 18, "timed_out": false, "_shards": { "total": 5, "successful": 5, "failed": 0 }, "hits": { "total": 2, "max_score": 1.0970675, "hits": [ { "_index": "blog", "_type": "user", "_id": "2", "_score": 1.5779335, "_source": { "nickname": "ease", "status": "normal" } }, { "_index": "blog", "_type": "user", "_id": "4", "_score": 1.0970675, "_source": { "nickname": "easy", "content": "simple", "status": "normal" } } ] } }
range
查詢用於數值等類型進行過濾,好比示例中過濾粉絲數大於等於2的用戶:
GET /user/naive/_search { "query": { "range": { "followerCount": { "gte": 2 }, "registerTime": { "gt": "2017-01-01 00:00:00", "lt": "2018-01-01 00:00:00" } } } }
示例中的range查詢能夠用SQL描述爲:
SELECT * FROM user_naive WHERE followerCount >= 2 AND unix_timestamp(registerTime) > unix_timestamp('2017-01-01 00:00:00') AND unix_timestamp(registerTime) < unix_timestamp('2018-01-01 00:00:00');
可用的範圍表達式有:
lt
: 小於(less than)lte
: 小於等於(less than / equals)gt
: 大於(greater than)gte
: 大於等於(greater than / equals)能夠進行範圍查詢的字段:
用戶輸入字符串一般沒法進行精確查詢,全文查詢可使用分析器解析查詢字符串而後根據相關度篩選查詢結果。
match
查詢全文字段(類型爲analyzed
)時,會使用分析器將查詢字符串解析成詞條列表,而後進行匹配。
查詢字符串"easy simple"會被standard分析器解析爲[easy
, simple
], 這個查詢等價於:
{ "terms": { "nickname": ["easy", "simple"] } }
POST /blog/user/_search { "query": { "match": { "nickname": "easy simple" } } } response: { "took": 19, "timed_out": false, "_shards": { "total": 5, "successful": 5, "failed": 0 }, "hits": { "total": 3, "max_score": 1.1382749, "hits": [ { "_index": "blog", "_type": "user", "_id": "3", "_score": 1.1382749, "_source": { "nickname": "simple", "status": "normal" } }, { "_index": "blog", "_type": "user", "_id": "1", "_score": 1.049597, "_source": { "nickname": "easy", "status": "normal" } } ] } }
若以eas sim
爲關鍵詞進行term查詢不會匹配到任何文檔。
multi_match
用於對多個字段進行同一個查詢:
{ "query": { "multi_match": { "analyzer": "keyword", "query": "easy", "fields": [ "nickname.ngram", "username.ngram" ] } } }
上述查詢等同於對nickname.ngram
和username.ngram
兩個字段進行match查詢,對結果進行綜合排序。
排序方式有:
best_fields
most_fields
cross_fields
script查詢可使用腳本描述查詢條件,進行復雜的查詢。
{ "query": { "script": { "script": { "source": "doc['count'].value > params.limit", "lang": "painless", "params": { "limit": 1 } } } }
咱們一般使用ElasticSearch提供的painless腳本語言編寫腳本,也可使用Groovy等腳本語言。
組合查詢用於將多個查詢組合起來,以表達更復雜的查詢條件或排序規則。
組合查詢都是能夠自由嵌套的,如咱們能夠bool
查詢中使用另外一個bool
查詢或dis_max
做爲must
子查詢。
Bool查詢用於組合多個條件查詢相關度最高的文檔, 下面展現了一個Bool查詢請求:
POST /user/naive/_search { "query": { "bool": { "must": { "match": { "nickname": "easy" } }, "must_not": { "match": { "nickname": "hard" } }, "should": { "match": { "nickname": "simple" } }, "filter": [ { "term": { "status": "normal" } } ] } } } response: { "took": 20, "timed_out": false, "_shards": { "total": 5, "successful": 5, "failed": 0 }, "hits": { "total": 3, "max_score": 1.3847495, "hits": [ { "_index": "blog", "_type": "user", "_id": "4", "_score": 1.3847495, "_source": { "nickname": "easy", "content": "simple", "status": "normal" } }, { "_index": "blog", "_type": "user", "_id": "5", "_score": 0.45532417, "_source": { "nickname": "easy", "content": "bitter", "status": "normal" } } ] } }
上述bool查詢的目標爲:
must
條件必須知足, 即nickname
字段必須與詞條easy
匹配,字段的匹配程度會影響得分must_not
條件必須不知足, 即nickname
字段不能與詞條hard
匹配should
條件不作要求, 但知足should
條件的文檔會得到更高的相關度評分_score
。 當should
查詢中包含多個字段時, 會將各字段得分的和做爲總分。因此查詢到兩個nickname與easy
匹配的文檔,可是content
爲simple
的字段得到了更高的評分。filter
條件必須知足,可是匹配程度不會影響得分。filter
子查詢通常使用精確查詢,由於過濾器不進行相關度計算且使用過濾器緩存, 其執行速度很是快。
上文已經提到bool
查詢的should
查詢會將各字段得分之和做爲總分,然而在實際應用中一般一個字段高度匹配的文檔可能比擁有多個字段低匹配更符合用戶的指望。
dismax查詢一樣用於組合多個查詢,可是按照匹配程度最高的字段肯定總分:
{ "query": { "dis_max": { "queries": [ { "match": { "nickname": "easy" } }, { "match": { "content": "easy" } } ] } } }
function_score能夠更加自由地控制評分過程:
{ "query": { "function_score": { "filter": { "term": { "uid": 1 } }, "functions": [ { "filter": { "term": { "features": "a" }}, "weight": 1 }, { "filter": { "term": { "features": "b" }}, "weight": 2 } ], "score_mode": "sum", } } }
一致性隨機
function_score
能夠對結果進行隨機排序:
{ "query": { "random_score": { "seed": 2 }, "bost_mode": "replace", "query": { "dis_max": { "queries": [ { "multi_match": { "analyzer": "keyword", "query": "finley", "boost": 1.2, "fields": [ "username.ngram" ] } }, { "multi_match": { "analyzer": "keyword", "query": "finley", "boost": 1, "fields": [ "nickname.ngram" ] } } ] } } } }
只要隨機種子random_score.seed
不變結果的排序就不會變化,這種方式被稱爲一致性隨機評分。
一致性隨機評分機制能夠爲每一個用戶生成一個獨有的排序,並支持翻頁瀏覽。
ElasticSearch的搜索結果默認按照_score
進行降序排列,_score
是根據TF-IDF算法得出文檔與查詢調價匹配度。
在一些狀況下咱們但願自定義排序方式, 好比按建立時間排列。
POST /blog/user/_search { "query" : { "term" : { "uid" : 1 } }, "sort": { "date": { "order": "desc" } } }
{ "query" : { "term" : { "uid" : 1 } }, "sort": { "script_score": { "source": "_score / (params.current - doc['create_at'].value)" "params": { "current": 1534606168 } } } }
ElasticSearch中的Index是最高級的邏輯的結構, 相似於MySQL中的數據庫(schema),能夠配置獨立的搜索策略和存儲策略。
ElasticSearch經過倒排索引進行搜索,所謂倒排索引是指對文檔進行分析提取關鍵詞,而後創建關鍵詞到文檔的索引,當咱們搜索關鍵詞時就能夠找到它所關聯的文檔。
咱們能夠經過在Index中配置分析器和映射來設置倒排索引的策略。
分析器是通用的從文檔提取關鍵詞的方法,即將文檔中某個字段映射爲關鍵字的方法。例如:過濾停用詞,分詞,添加同義詞等。
映射則是具體指定文檔中的某個字段應該使用什麼分析器來提取關鍵詞。
這個拆分的過程便是分析的過程, 分析執行的操做包括不限於: 字符過濾, 分詞, 停用詞過濾, 添加同義詞.
ES提供了不少內置分析器:
standard
: 默認分析器, 根據Unicode定義刪除標點並將詞條小寫simple
: 根據空格分詞並將詞條小寫whitespace
: 根據空格分詞但不將詞條小寫english
: 過濾英文停用詞並將詞條還原爲詞根, 詳情參考官方文檔.ngram
: 滑動窗口分析器,取文本中全部子串做爲關鍵詞。 好比對easy
進行處理能夠獲得關鍵詞:e
, a
, s
, y
, ea
, as
, sy
, eas
, asy
, easy
。edge-ngram
: 邊緣固定滑動窗口分析器,取文本全部從頭開始的子串做爲關鍵詞。 好比對easy
進行處理能夠獲得關鍵詞:e
, ea
, eas
, easy
。經常使用於聯想搜索,根據用戶輸入前幾個字符進行搜索。此外, 也能夠經過配置字符過濾器(char_filter
), 詞過濾器(filter
), 分詞器(tokenizer
)的方式來自定義分析器。
這裏展現基於ngram的分析器定義:
PUT /blog { "settings": { "analysis": { "filter": { "grams_filter": { "type": "ngram", "min_gram": 1, "max_gram": 5 } }, "analyzer": { "gram_analyzer": { "type": "custom", "tokenizer": "standard", "filter": [ "lowercase", "grams_filter" ] } } } } }, mappings: {...} }
自定義分析器的更多信息能夠查閱官方文檔:
映射則是具體指定文檔中的某個字段應該使用什麼分析器來提取關鍵詞:
PUT /blog { "settings": { ... }, "mappings": { "user": { "properties": { "nickname": { "type": "string", "analyzer": "gram_analyzer", "fields": { "keyword:": { "type": "keyword" } } }, "status": { "type": "text", "fields": { "keyword:": { "type": "keyword" } } } } } } }
上述JSON中user
項定義了一個根對象, 它一般與文檔對應。根對象下能夠包含下列幾個字段:
文檔中每個字段都有3個配置項:
type
: 指定字段類型, 如:text
, long
, double
和date
.index
: 指定字段索引的類型:
no
: 不可被搜索not_analyzed
: 必須精確匹配analyzed
: 使用分析器創建倒排索引analyzer
: 該字段使用的默認分析器fields
: 字段的屬性, 能夠配置獨立的type, index和analyzer。用於將一個字段映射爲不一樣類型適應不一樣用途。在分析器及映射兩節中展現了建立索引所需的PUT請求片斷,將類型和映射一節中PUT請求的settings字段, 用分析器一節中的settings字段替換便可獲得完整建立索引請求。
發送DELETE請求能夠刪除索引:
DELETE /user
: 刪除user索引DELET /user1,user2
: 刪除user1和user2兩個suoyinDELETE /user*
: 根據通配符刪除索引DELET /_all
, DELETE /*
: 刪除全部索引GET /_cat/indices
能夠列出ElasticSearch上的全部索引。
GET /blog?pretty
列出索引blog的全部信息。
若須要進行中文搜索咱們須要使用中文分析器,它的核心是中文分詞器(tokenizer)。
這裏咱們使用插件elastic-analysis-ik進行中文搜索。
PUT /post/Post { "settings": { "analysis": { "analyzer": { "cn_smart": { "type": "custom", "tokenizer": "ik_smart", "filter": [ { "type": "length", "min": "3" } ] }, "max_word": { "type": "custom", "tokenizer": "ik_max_word", "filter": [ { "type": "length", "min": "3" } ] } } } }, "mappings": { "user": { "properties": { "content": { "type": "text", "analyzer": "cn_smart", "fields": { "max_word": { "type": "text", "analyzer": "max_word" } } } } } } }
使用match進行查詢:
{ "query" : { "match" : { "content" : "搜索" } } }
{ "query" : { "match" : { "content.max_word" : "搜索" } } }
ik_smart
會進行標準的中文分詞, ik_max_word
則會試圖窮盡全部分詞