背景:
公司最近的項目涉及到ES查詢,空余之中對ES進行了一個入門的學習,ES真是個強大的搜索引擎。
ES 入門語法(ES對document 文檔的增刪改查)
1 #獲取所有索引 2 GET _search 3 { 4 "query": { 5 "match_all": {} 6 } 7 } 8 #獲取集群的健康狀態 9 GET /_cat/health?v 10 #獲取ES節點 11 GET /_cat/nodes?v 12 #獲取所有index 13 GET /_cat/indices?v 14 #獲取es的健康狀態,索引 15 GET /_cat/indices?v&h=health,status,index 16 PUT /xinhua 17 { 18 "acknowledged": true, 19 "shards_acknowledged": true, 20 "index": "xinhua" 21 } 22 GET /question_content/all 23 #在es里創建一個索引為megacorp,索引為employee ,id 為1的第一條數據 24 25 #將 HTTP 命令由 PUT 改為 GET 可以用來檢索文檔,同樣的,可以使用 DELETE 命令來刪除文檔,以及使用 HEAD 指令來檢查文檔是否存在。如果想更新已存在的文檔,只需再次 PUT 26 PUT /megacorp/employee/1 27 { 28 "first_name" : "John", 29 "last_name" : "Smith", 30 "age" : 25, 31 "about" : "I love to go rock climbing", 32 "interests": [ "sports", "music" ] 33 } 34 35 GET /megacorp/employe/1 36 PUT /megacorp/employee/2 37 { 38 "first_name" : "Jane", 39 "last_name" : "Smith", 40 "age" : 32, 41 "about" : "I like to collect rock albums", 42 "interests": [ "music" ] 43 } 44 PUT /megacorp/employee/3 45 { 46 "first_name" : "Douglas", 47 "last_name" : "Fir", 48 "age" : 35, 49 "about": "I like to build cabinets", 50 "interests": [ "forestry" ] 51 } 52 GET /megacorp/employee/1 53 #查看文檔是否存在 54 HEAD /megacorp/employee/1 55 #檢索文檔 56 GET /megacorp/employee/_search 57 #條件檢索文檔,查找出last_name = Smith的雇員 58 GET /megacorp/employee/_search?q=last_name:Smith 59 #ES DSL 查詢語句,可以拼接更多的查詢條件,后面會介紹 60 GET /megacorp/employee/_search 61 { 62 "query": { 63 "match": { 64 "last_name": "Smith" 65 } 66 } 67 68 } 69 70 71 72 73 #按照組合條件搜索,查詢出last_name = Smith,且年齡大於30歲的雇員,gte為大於 74 GET /megacorp/employee/_search 75 { 76 "query": { 77 "bool": { 78 "must": 79 { 80 "match": { 81 "last_name": "Smith" 82 } 83 }, 84 "filter": 85 {"range": { 86 "age": { 87 "gte": 30 88 } 89 }} 90 91 } 92 } 93 } 94 #ES默認全文匹配含有的搜索 95 GET /megacorp/employee/_search 96 { 97 "query": { 98 "match": { 99 "about": "rock climbing" 100 } 101 } 102 } 103 #短語搜索,查詢 "rock climbing" 短語存在的雇員 104 GET /megacorp/employee/_search 105 { 106 "query": { 107 "match_phrase": { 108 "about": "rock climbing" 109 } 110 } 111 } 112 #高亮搜索 113 GET /megacorp/employee/_search 114 { 115 "query": { 116 "match_phrase": { 117 "about": "rock climbing" 118 } 119 }, 120 "highlight": { 121 "fields": { 122 "about":{} 123 } 124 } 125 } 126 #分析 127 #終於到了最后一個業務需求:支持管理者對員工目錄做分析。 #Elasticsearch 有一個功能叫聚合(aggregations),允許我們基於##數據生成一些精細的分析結果。聚合與 SQL 中的 GROUP BY #類似但更強大。 128 #舉個例子,挖掘出員工中最受歡迎的興趣愛好: 129 130 GET /megacorp/employee/_search 131 { 132 "aggs": { 133 "all_interests": { 134 "terms": { "field": "interests" } 135 } 136 } 137 } 138 #坑1:從異常信息中可以看出,是因為我要聚合的字段【interests】沒有進行優化,也類似沒有加索引。沒有優化的字段es默認是禁止聚合/排序操作的。所以需要將要聚合的字段添加優化 139 PUT /megacorp/_mapping 140 { 141 "properties": { 142 "interests": { 143 "type": "text", 144 "fielddata": true 145 } 146 } 147 }
官方文檔:https://www.elastic.co/guide/cn/elasticsearch/guide/current/index.html