經過兩天的介紹,今天來點實作,從一般的 CRUD -> 實踐基礎全文檢索
安裝、實作連結參考 : https://www.elastic.co/cn/downloads/elasticsearch
基本 RESTful API
PUT 寫入、修改
localhost:9200/customer/_doc/1
// index : customer
// type : _doc 雖然已經被取消,但還是需要提供
// 1 : 此筆資料的 id
{
"name": "John Doe"
}
retrun :
{
"_index": "customer",
"_type": "_doc",
"_id": "1",
"_version": 3,
"result": "updated",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
},
"_seq_no": 3,
"_primary_term": 4
}
// 透過同 id 進行修改
// 修改方式為整筆覆蓋,如果JSON中沒有 name 欄位,則新資料只會有 age
http://localhost:9200/customer/_doc/1
{
"name": "John Doe",
"age": 14
}
POST 抓取整個 node 的資料
localhost:9200/customer/_search
{
"took": 47,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 2,
"relation": "eq"
},
"max_score": 1,
"hits": [
{
"_index": "customer",
"_type": "_doc",
"_id": "1",
"_score": 1,
"_source": {
"name": "John Doe"
}
}
]
}
}
GET 透過 id 於 index 中抓取該筆資料
localhost:9200/customer/_doc/1
{
"_index": "customer",
"_type": "_doc",
"_id": "1",
"_version": 3,
"_seq_no": 3,
"_primary_term": 4,
"found": true,
"_source": {
"name": "John Doe"
}
}
以 JAVA code 介紹全文檢索的條件組成
QueryBuilder :基本搜尋條件,需定義變數名稱 (QueryBuilder xxx = )
// matchQuery 字串比對 (預設模糊)
QueryBuilders.matchQuery("personId", personId);
// multiMatchQuery : 多欄位比對 (預設模糊)
QueryBuilders.multiMatchQuery(query, "personName", "personRelationType", "personRelationRole")
// rangeQuery : 數值比對
QueryBuilders.rangeQuery(year).gte(from).lte(to);
// fuzziness : 模糊搜索 (預設)
fuzziness("AUTO");
BoolQueryBuilder : 用於組合搜尋
// 可透過此程式碼自定:2
boolQueryBuilder.minimumShouldMatch(2);
SearchSourceBuilder : 搜尋最終條件 (排序、條件)
// sort 時間排序
sourceBuilder.sort("personRelationUpdateDate", SortOrder.DESC);
sourceBuilder.query(boolQueryBuilder);
最後以 API 進行說明組合 -> 全文檢索
上述 Java code 組合可達到相同效果
POST + 組合條件
localhost:9200/customer/_doc
body :
{
"query": {
"bool": {
"must": [
{ "match": { "city": "Tai" } }
],
"must_not": [
{ "match": { "weight": "50" } }
]
}
}
}
response :
{
"took": 2,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 1,
"relation": "eq"
},
"max_score": 0.2876821,
"hits": [
{
"_index": "customer",
"_type": "_doc",
"_id": "1",
"_score": 0.2876821,
"_source": {
"name": "John Doe",
"height": 180,
"weight": 70,
"city": "Taipei"
}
}
]
}
}
最後需從 "hits": 中將資料抓出,實作完成~
Kibana 這次沒有寫出實作,實際玩起來感覺感覺蠻深蠻炫的
明天以一路上踩的雷 + 解析 Google 進階搜索進行收尾
來源 :
https://www.dotblogs.com.tw/supershowwei/2015/12/01/112117
https://zhuanlan.zhihu.com/p/72974595
https://godleon.github.io/blog/Elasticsearch/Elasticsearch-getting-started/
https://blog.toright.com/posts/5319/fulltext-search-elasticsearch-kibana-bigdata.html