一、簡介
ElasticSearch是一個基於Lucene的搜索服務器,它提供了一個基於RESTful web接口分布式多用戶能力的全文搜索引擎,ElasticSearch是用於Java語言開發的,並作為Apache許可條款下的開放源碼發布,是一種流行的企業級搜索引擎。
二、parent/child關系
可以為兩個完全分開的文檔,按某種對應關系以一對多的關系映射從而關聯上,更新符文檔時,子文檔不會重新被索引,子文檔更新不會影響父文檔或者其他子文檔,
三、關聯查詢
這里我們先創建一個es,
PUT school_test { "mappings": { "properties": { "id": { "type": "keyword" }, "class_name": { "type": "keyword" }, "teacher_name": { "type": "keyword" }, "student_name": { "type": "keyword" }, "index_create_time_dt": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } }, "index_update_time_dt": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } }, "parent_child_t": { "type": "join", "eager_global_ordinals": true, "relations": { "parent": "child" } }, "routing": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } } } } }
結構中含有class_name, teacher_name, student_name。其中關聯關系為parent-child,
創建測試數據
通過子級查詢父級(has_child)
例:通過子級條件class_name=“教師1”查詢出所在的班級
{ "query": { "bool": { "must": [ { "term": { "role": { "value": "class" } } }, { "has_child": { "type": "child", "query": { "term": { "class_name": { "value": "教師1" } } } } } ] } } }
查詢結果如圖:
通過父級查詢子級(has_parent)
例:通過父級條件class_name="班級1",查詢出所有教師
{ "query": { "bool": { "must": [ { "term": { "role": { "value": "teacher" } } }, { "has_parent": { "parent_type": "parent", "query": { "term": { "class_name": { "value": "班級1" } } } } } ] } } }
查詢結果如圖所示:
但是如果整體的結構為三層結構,即班級對應 -> 教師 -> 學生,映射關系parent-child,已經不能滿足查詢條件了
例如通過教師查詢對應的學生,
這個查詢條件得到的查詢結果將為空,所以需要將對應關系變為
"relations": {
"class": "teacher",
"teacher": "student"
}
祖孫輩關聯查詢
三級關聯以上可以看為祖孫被查詢,例如通過class_name="班級2“查詢出所有學生
{ "query": { "bool": { "must": [ { "term": { "role": { "value": "student" } } }, { "has_parent": { "parent_type": "teacher", "query": { "has_parent": { "parent_type": "class", "query": { "term": { "class_name": { "value": "班級2" } } } } } } } ] } } }
查詢結果:
注:建立對應關系時,要注意父文檔和子文檔在es的同一分片上,這里保持routing統一才可以關聯查詢到數據