query phase
壹次請求要打到所有shard的壹個replica/primary上去,如果每個shard都有多個replica,那麽同時並發過來的搜索請求可以同時打到其他的replica上去
search的參數都是類似 ,beijing 作為這壹條document的_all field的值,同時進行分詞後建立對應的倒排索引
DSL - Domain Specified Language , 特殊領域的語言。
請求參數是請求體傳遞的。在Elasticsearch中,請求體的字符集默認為UTF-8。
query string 後邊的參數原來越多,搜索條件越來越復雜,不能滿足需求。
DSL:Domain Specified Language,特定領域的語言
es特有的搜索語言,可在請求體中攜帶搜索條件,功能強大。
查詢全部 GET /book/_search
排序 GET /book/_search?sort=price:desc
分頁查詢 GET /book/_search?size=10&from=0
指定返回字段 GET /book/ _search? _source=name,studymodel
通過組合以上各種類型查詢,實現復雜查詢。
搜索需求:title必須包含elasticsearch,content可以包含elasticsearch也可以不包含,author_id必須不為111
初始數據:
搜索:
返回:
更復雜的搜索需求:
select * from test_index where name='tom' or (hired =true and (personality ='good' and rude != true ))
重新創建book索引
插入數據
搜索
relevance score算法,簡單來說,就是計算出,壹個索引中的文本,與搜索文本,他們之間的關聯匹配程度。
Elasticsearch使用的是 term frequency/inverse document frequency算法,簡稱為TF/IDF算法。TF詞頻(Term Frequency),IDF逆向文件頻率(Inverse Document Frequency)
Term frequency :搜索文本中的各個詞條在field文本中出現了多少次,出現次數越多,就越相關。
舉例:搜索請求:hello world
doc1 : hello you and me,and world is very good.
doc2 : hello,how are you
Inverse document frequency :搜索文本中的各個詞條在整個索引的所有文檔中出現了多少次,出現的次數越多,就越不相關.
舉例:搜索請求:hello world
doc1 : hello ,today is very good
doc2 : hi world ,how are you
整個index中1億條數據。hello的document 1000個,有world的document 有100個。
doc2 更相關
Field-length norm :field長度,field越長,相關度越弱
舉例:搜索請求:hello world
doc1 : {"title":"hello article","content ":"balabalabal 1萬個"}
doc2 : {"title":"my article","content ":"balabalabal 1萬個,world"}
返回
搜索的時候,要依靠倒排索引;排序的時候,需要依靠正排索引,看到每個document的每個field,然後進行排序,所謂的正排索引,其實就是doc values
在建立索引的時候,壹方面會建立倒排索引,以供搜索用;壹方面會建立正排索引,也就是doc values,以供排序,聚合,過濾等操作使用
doc values是被保存在磁盤上的,此時如果內存足夠,os會自動將其緩存在內存中,性能還是會很高;如果內存不足夠,os會將其寫入磁盤上
倒排索引
doc1: hello world you and me
doc2: hi, world, how are you
搜索時:
hello you --> hello, you
hello --> doc1
you --> doc1,doc2
doc1: hello world you and me
doc2: hi, world, how are you
sort by 出現問題
正排索引
doc1: { "name": "jack", "age": 27 }
doc2: { "name": "tom", "age": 30 }
壹般搜索,如果不加from和size,就默認搜索前10條,按照_score排序
短語檢索。要求查詢條件必須和具體數據完全匹配才算搜索結果。其特征是:1-搜索條件不做任何分詞解析;2-在搜索字段對應的倒排索引(正排索引)中進行精確匹配,不再是簡單的全文檢索。
決定了哪些shard會被用來執行搜索操作
_primary, _primary_first, _local, _only_node:xyz, _prefer_node:xyz, _shards:2,3
bouncing results問題,兩個document排序,field值相同;不同的shard上,可能排序不同;每次請求輪詢打到不同的replica shard上;每次頁面上看到的搜索結果的排序都不壹樣。這就是bouncing result,也就是跳躍的結果。
搜索的時候,是輪詢將搜索請求發送到每壹個replica shard(primary shard),但是在不同的shard上,可能document的排序不同
解決方案就是將preference設置為壹個字符串,比如說user_id,讓每個user每次搜索的時候,都使用同壹個replica shard去執行,就不會看到bouncing results了
主要就是限定在壹定時間內,將部分獲取到的數據直接返回,避免查詢耗時過長
document文檔路由,_id路由,routing=user_id,這樣的話可以讓同壹個user對應的數據到壹個shard上去
default:query_then_fetch
dfs_query_then_fetch,可以提升revelance sort精準度