ES練習代碼


  

  1 package elasticsearch;
  2 
  3 import java.util.HashMap;
  4 import java.util.List;
  5 import java.util.Map;
  6 
  7 import org.elasticsearch.action.bulk.BulkItemResponse;
  8 import org.elasticsearch.action.bulk.BulkRequestBuilder;
  9 import org.elasticsearch.action.bulk.BulkResponse;
 10 import org.elasticsearch.action.delete.DeleteRequest;
 11 import org.elasticsearch.action.delete.DeleteResponse;
 12 import org.elasticsearch.action.deletebyquery.DeleteByQueryResponse;
 13 import org.elasticsearch.action.get.GetResponse;
 14 import org.elasticsearch.action.index.IndexRequest;
 15 import org.elasticsearch.action.index.IndexResponse;
 16 import org.elasticsearch.action.search.SearchResponse;
 17 import org.elasticsearch.action.search.SearchType;
 18 import org.elasticsearch.action.update.UpdateResponse;
 19 import org.elasticsearch.client.transport.TransportClient;
 20 import org.elasticsearch.cluster.node.DiscoveryNode;
 21 import org.elasticsearch.common.collect.ImmutableList;
 22 import org.elasticsearch.common.settings.ImmutableSettings;
 23 import org.elasticsearch.common.settings.Settings;
 24 import org.elasticsearch.common.text.Text;
 25 import org.elasticsearch.common.transport.InetSocketTransportAddress;
 26 import org.elasticsearch.common.transport.TransportAddress;
 27 import org.elasticsearch.common.xcontent.XContentBuilder;
 28 import org.elasticsearch.common.xcontent.XContentFactory;
 29 import org.elasticsearch.index.query.QueryBuilders;
 30 import org.elasticsearch.search.SearchHit;
 31 import org.elasticsearch.search.SearchHits;
 32 import org.elasticsearch.search.aggregations.AggregationBuilders;
 33 import org.elasticsearch.search.aggregations.bucket.terms.Terms;
 34 import org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket;
 35 import org.elasticsearch.search.aggregations.metrics.sum.Sum;
 36 import org.elasticsearch.search.highlight.HighlightField;
 37 import org.elasticsearch.search.sort.SortOrder;
 38 import org.junit.Before;
 39 import org.junit.Test;
 40 
 41 import com.fasterxml.jackson.databind.ObjectMapper;
 42 
 43 public class TestEs {
 44     
 45     TransportClient transportClient = new TransportClient();
 46     //before表示在執行每個test方法之前運行
 47     @Before
 48     public void test0() throws Exception {
 49         //指定es集群中的節點信息
 50         TransportAddress transportAddress = new InetSocketTransportAddress("192.168.1.99",9300);
 51         //TransportAddress transportAddress1 = new InetSocketTransportAddress("192.168.1.98",9300);
 52         transportClient.addTransportAddresses(transportAddress);
 53     }
 54     
 55     /**
 56      * 通過java代碼操作es-1
 57      * 在實際工作中這樣寫不是很靠譜,需要完善,做測試可以
 58      * @throws Exception
 59      */
 60     @Test
 61     public void test1() throws Exception {
 62         //通過TransportClient可以和es集群交互
 63         //TransportClient transportClient = new TransportClient();
 64         
 65         //指定es集群中的節點信息, 這個地方指定的端口是節點和節點之間的通信端口是9300,不是Http請求的端口9200.
 66         TransportAddress transportAddress = new InetSocketTransportAddress("192.168.1.99",9300);
 67         TransportAddress transportAddress1 = new InetSocketTransportAddress("192.168.1.98",9300);
 68         transportClient.addTransportAddresses(transportAddress,transportAddress1);//加入多個地址
 69         
 70         //獲取當前transportClient連接到了集群多少個節點
 71         ImmutableList<DiscoveryNode> connectedNodes = transportClient.connectedNodes();
 72         for (DiscoveryNode discoveryNode : connectedNodes) {
 73             System.out.println(discoveryNode.getHostAddress());//打印192.168.1.99;192.168.1.98
 74             //如果加入transportClient.addTransportAddresses(transportAddress)  只有一個ip,打印的就只有一個.
 75         }
 76     }
 77     
 78     
 79     
 80     /**
 81      * 通過java代碼操作es-2
 82      * 實際工作中使用的時候建議加上下面這些配置信息
 83      * @throws Exception
 84      */
 85     @Test
 86     public void test2() throws Exception {
 87         //指定es的配置信息   Immutable不可改變的;
 88         Settings settings = ImmutableSettings.settingsBuilder()
 89                 .put("cluster.name", "elasticsearch")//如果集群名稱在配置文件中被修改了,那么在這需要顯式定義一下
 90                 //es集群名稱默認是 elasticsearch  sniff嗅; 發現;
 91                 .put("client.transport.sniff", true)//開啟集群的嗅探功能,這樣可以保證es會自動把集群中的其他節點信息添加到transportClient里面
 92                 //開啟嗅探功能后 只要指定集群中的任意一個可用節點就可以了.當把代碼運行之后TransportClient里面會把集群中所有節點的信息都拿到,能識別集群中的所有節點.
 93                 .build();
 94         
 95         //通過TransportClient可以和es集群交互
 96         TransportClient transportClient = new TransportClient(settings);
 97         //指定es集群中的節點信息
 98         TransportAddress transportAddress = new InetSocketTransportAddress("192.168.1.99",9300);
 99         transportClient.addTransportAddresses(transportAddress);
100         
101         //獲取當前transportClient連接到了集群多少個節點
102         ImmutableList<DiscoveryNode> connectedNodes = transportClient.connectedNodes();
103         for (DiscoveryNode discoveryNode : connectedNodes) {
104             System.out.println(discoveryNode.getHostAddress()); //雖然前面只指定了1.99 但是打印192.168.1.99  192.168.1.98
105         }
106     }
107     
108     String index = "crxy";
109     String type = "emp";    
110     /**
111      * index-1
112      * @throws Exception
113      */
114     @Test
115     public void test3() throws Exception {
116         String jsonStr = "{\"name\":\"zs\",\"age\":20}";//向索引庫中傳入一個String字符串,還可以接受其他類型
117         IndexResponse indexResponse = transportClient.prepareIndex(index, type, "7")//添加一個id=7的數據
118                             .setSource(jsonStr)
119                             //.execute().actionGet();   這個和下面的get()方法是一樣的,get()就是對.execute().actionGet() 進行了封裝
120                             .get();//執行
121         System.out.println(indexResponse.getVersion());//得到這個數據的version,如果version=1代表是新添加的數據
122     }
123     
124     /**
125      * index-2
126      * 實際工作中使用
127      * @throws Exception
128      */
129     @Test
130     public void test4() throws Exception {//把hashmap類型的數據放入index庫
131         HashMap<String, Object> hashMap = new HashMap<String, Object>();
132         hashMap.put("name", "heeh");
133         hashMap.put("age", 20);
134         IndexResponse indexResponse = transportClient.prepareIndex(index, type, "8").setSource(hashMap).get();
135         System.out.println(indexResponse.getVersion());
136     }
137     
138     /**
139      * index -3
140      * 實際工作中使用
141      * 使用對象的時候需要把對象中的屬性轉化成json字符串
142      * 
143      * <dependency>
144             <groupId>com.fasterxml.jackson.core</groupId>
145             <artifactId>jackson-databind</artifactId>
146             <version>2.1.3</version>
147         </dependency>
148      * @throws Exception
149      */
150     @Test
151     public void test5() throws Exception {//傳入一個對象到index索引庫
152         Person person = new Person();
153         person.setName("lisi");
154         person.setAge(30);
155         
156         //如果直接傳入一個person對象會報錯,java.lang.IllegalArgumentException,必須把對象轉換成一個Json字符串,使用jackson依賴
157         //IndexResponse indexResponse = transportClient.prepareIndex(index, type, "9").setSource(person).get();
158         
159         ObjectMapper objectMapper = new ObjectMapper();
160         IndexResponse indexResponse = transportClient.prepareIndex(index, type, "9").setSource(objectMapper.writeValueAsString(person)).get();
161         System.out.println(indexResponse.getVersion());
162     }
163     
164     /**
165      * index -4
166      * 測試數據這樣使用
167      * @throws Exception
168      */
169     @Test
170     public void test6() throws Exception {
171         XContentBuilder builder = XContentFactory.jsonBuilder()//XContentFactory 這個是ES官方提供的可以構建Json字符串的工具類.
172                 .startObject()//{
173                 .field("name", "zs")
174                 .field("age", 18)
175                 .endObject();//}
176         IndexResponse indexResponse = transportClient.prepareIndex(index, type, "11").setSource(builder).get();
177         System.out.println(indexResponse.getVersion());
178     }
179     
180     
181     
182     /**
183      * 查詢 通過id
184      * @throws Exception
185      */
186     @Test
187     public void test7() throws Exception {
188         GetResponse getResponse = transportClient.prepareGet(index, type, "9").get();//查詢id為9的數據
189         System.out.println(getResponse.getSourceAsString());
190     }
191     
192     /**
193      * 局部更新
194      * @throws Exception
195      */
196     @Test
197     public void test8() throws Exception {
198         XContentBuilder builder = XContentFactory.jsonBuilder().startObject().field("age", 19).endObject();
199         UpdateResponse updateResponse = transportClient.prepareUpdate(index, type, "9").setDoc(builder).get();
200         System.out.println(updateResponse.getVersion());//version打印2 數據更新
201     }
202     
203     /**
204      * 刪除-通過id刪除
205      * @throws Exception
206      */
207     @Test
208     public void test9() throws Exception {
209         DeleteResponse deleteResponse = transportClient.prepareDelete(index, type, "5").get();//刪除比較簡單
210     }
211     
212     /**
213      * 求總數
214      * 類似於mysql中的select count(*)
215      * @throws Exception
216      */
217     @Test
218     public void test10() throws Exception {//查找索引庫中的數據個數
219         long count = transportClient.prepareCount(index).get().getCount();
220         System.out.println(count);
221     }
222     
223     
224     /**
225      * 批量操作 bulk
226      * @throws Exception
227      */
228     @Test
229     public void test11() throws Exception {
230         BulkRequestBuilder bulkBuilder = transportClient.prepareBulk();
231         
232         IndexRequest indexRequest = new IndexRequest(index, type, "12");
233         XContentBuilder builder = XContentFactory.jsonBuilder().startObject().field("name", "haha").field("age", 18).endObject();
234         indexRequest.source(builder);
235         
236         DeleteRequest deleteRequest = new DeleteRequest(index, type, "13");
237         
238         bulkBuilder.add(indexRequest);//bulkBuilder中可以添加多個操作,這里一個是建立索引的操作,一個是刪除的操作.
239         bulkBuilder.add(deleteRequest);
240         
241         BulkResponse bulkResponse = bulkBuilder.get();
242         if(bulkResponse.hasFailures()){//批量操作中可能有的操作會出現問題,這個地方對操作失敗的處理
243             //獲取所有錯誤信息,並打印
244             BulkItemResponse[] items = bulkResponse.getItems();
245             for (BulkItemResponse bulkItemResponse : items) {
246                 System.out.println(bulkItemResponse.getFailureMessage());
247             }
248         }else{
249             System.out.println("全部OK");    
250         }
251         
252     }
253     
254     
255     /**
256      * 查詢
257      * lt:小於
258      * lte:小於等於
259      * gt:大於
260      * gte:大於等於
261      * 
262      * @throws Exception
263      */
264     @Test
265     public void test12() throws Exception {
266         SearchResponse searchResponse = transportClient.prepareSearch(index)//指定索引庫
267             .setTypes(type)//指定類型
268             .setQuery(QueryBuilders.matchQuery("name", "zs"))//指定查詢條件,不支持通配符
269             //.setQuery(QueryBuilders.multiMatchQuery("zs", "name","title"))//根據多個屬性進行查詢
270             //.setQuery(QueryBuilders.matchAllQuery())//查詢所有
271             //.setQuery(QueryBuilders.queryString("name:z* AND age:20"))//支持通配符* ?,可以實現復雜查詢,可以使用AND OR 之類的運算符(運算符要大寫)
272             //.setQuery(QueryBuilders.termQuery("name", "zs"))//在查詢的時候不分詞,主要針對 人名 地名等特殊的詞語
273             //工作中沒有說明特殊需求,就是用默認的查詢類型,如果對搜索准確度要求非常高,建議使用DFS_QUERY_THEN_FETCH,如果只追求查詢效果,對其他的指標不關心,可以使用QUERY_AND_FETCH
274             .setSearchType(SearchType.QUERY_THEN_FETCH)//指定查詢類型,可以指定四種
275             .setExplain(true)//返回的數據按照搜索詞的相關度排序
276             //分頁參數
277             .setFrom(0)
278             .setSize(10)
279             //根據某一個字段排序
280             .addSort("age",SortOrder.DESC)
281             //過濾
282             //.setPostFilter(FilterBuilders.rangeFilter("age").from(0).to(18).includeLower(true).includeUpper(false))//默認是閉區間
283             //.setPostFilter(FilterBuilders.rangeFilter("age").gt(0).lt(18))
284             //實現高亮
285             .addHighlightedField("name")//設置高亮字段
286             .setHighlighterPreTags("<font color='red'>")//設置高亮前綴和后綴
287             .setHighlighterPostTags("</font>")
288             .get();
289         SearchHits hits = searchResponse.getHits();
290         long totalHits = hits.getTotalHits();
291         System.out.println("總數:"+totalHits);
292         SearchHit[] hits2 = hits.getHits();
293         for (SearchHit searchHit : hits2) {
294             //獲取高亮內容
295             Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
296             HighlightField highlightField = highlightFields.get("name");
297             if(highlightField!=null){
298                 String name_h = "";
299                 Text[] fragments = highlightField.fragments();
300                 for (Text text : fragments) {
301                     name_h+=text;
302                 }
303                 System.out.println("高亮內容:"+name_h);
304             }
305             System.out.println(searchHit.getSourceAsString());
306         }
307     }
308     
309     //ES是一個分布式是搜索引擎,天生就是為分布式而生的,但是分布式有優點,也是有缺點.
310     //一個索引庫crxy的數據分布到了5個分片,去哪個分片去查,由於是分布式,可能每個分片中都有數據,所以一定要到所有分片中去查找.
311     
312     
313     
314     /**
315      * 根據查詢條件刪除數據
316      * @throws Exception
317      */
318     @Test
319     public void test13() throws Exception {
320         DeleteByQueryResponse deleteByQueryResponse = transportClient.prepareDeleteByQuery(index)
321                 .setQuery(QueryBuilders.matchAllQuery())
322                 .get();
323     }
324     
325     
326     /**
327      * 統計分析-count
328      * 根據年齡進行分組,統計相同年齡的數據有多少條
329      * 
330      * 默認情況下,如果分組個數大於10條的話,默認只會返回前10條分組數據
331      * 如果想獲取所有分組數據,或者想要獲取指定數量的分組數據,如何實現呢?
332      *     .size(0)
333      * 
334      * @throws Exception
335      */
336     @Test
337     public void test14() throws Exception {
338         SearchResponse searchResponse = transportClient.prepareSearch(index)
339             .setTypes(type)
340             .addAggregation(AggregationBuilders.terms("age_term").field("age").size(0))//給分組起個名稱,並且指定分組字段
341             .get();
342         
343         Terms terms = searchResponse.getAggregations().get("age_term");//指定分組的名字.
344         //獲取分組數據
345         List<Bucket> buckets = terms.getBuckets();
346         for (Bucket bucket : buckets) {
347             System.out.println(bucket.getKey()+"----"+bucket.getDocCount());
348         }
349     }
350     /*打印
351      21----3
352      18----2
353      19----1
354      20----1
355      */
356     
357     
358     /**
359      * 統計分析-sum   select name,sum(score) from table group by name;
360      * 需要使用.subAggregation
361      * @throws Exception
362      */
363     /**
364          使用數據:
365         #aggregations-2
366         curl -XPUT 'localhost:9200/crxy/emp/1' -d'{"name":"zs","score":60}'
367         curl -XPUT 'localhost:9200/crxy/emp/2' -d'{"name":"zs","score":90}'
368         curl -XPUT 'localhost:9200/crxy/emp/3' -d'{"name":"ls","score":80}'
369         curl -XPUT 'localhost:9200/crxy/emp/4' -d'{"name":"ls","score":70}'
370      */
371     @Test
372     public void test15() throws Exception {
373         SearchResponse searchResponse = transportClient.prepareSearch(index)
374             .setTypes(type)
375             .addAggregation(AggregationBuilders.terms("name_term").field("name")//指定分組字段
376                     .subAggregation(AggregationBuilders.sum("score_sum").field("score")))//指定求sum的字段
377             .get();
378         
379         Terms terms = searchResponse.getAggregations().get("name_term");
380         List<Bucket> buckets = terms.getBuckets();
381         for (Bucket bucket : buckets) {
382             Sum sum = bucket.getAggregations().get("score_sum");
383             System.out.println(bucket.getKey()+"----"+sum.getValue());
384         }
385     }
386     /*
387      * 打印輸出
388         ls----150.0
389         zs----150.0
390      */
391     
392     
393     /**
394      * 指定分片查詢(_shards),指定某個節點(_only_node)和某些節點(自定義的_only_nodes)
395      * @throws Exception
396      */
397     @Test
398     public void test16() throws Exception {
399         SearchResponse searchResponse = transportClient.prepareSearch(index)
400                 .setTypes(type)
401                 .setQuery(QueryBuilders.matchAllQuery())
402                 //.setPreference("_shards:0,2") //.setPreference("_local")   .setPreference("")
403                 .setPreference("_only_node:8PoWbRVvQQ6NU283Bfd_7A,BJwexRvDTJ-VRx7Njs8uxA")//8PoWbRVvQQ6NU283Bfd_7A是一個節點的id
404                 .get();
405         
406         SearchHits hits = searchResponse.getHits();
407         long totalHits = hits.getTotalHits();
408         System.out.println("總數:"+totalHits);
409         SearchHit[] hits2 = hits.getHits();
410         for (SearchHit searchHit : hits2) {
411             System.out.println(searchHit.getSourceAsString());
412         }
413     }
414     
415 }

 

 

 1     @Test
 2     public void test16() throws Exception {
 3         SearchResponse searchResponse = transportClient.prepareSearch("crxy*")
 4                 .setTypes(type)
 5                 .setQuery(QueryBuilders.matchAllQuery())
 6                 //查詢指定分片的數據可以使用下面這兩種方案,第一種直接指定分片id,第二種根據routing參數的值計算分片id
 7                 //.setPreference("_shards:0")
 8                 //.setRouting("hehe")
 9                 .get();
10         
11         SearchHits hits = searchResponse.getHits();
12         long totalHits = hits.getTotalHits();
13         System.out.println("總數:"+totalHits);
14         SearchHit[] hits2 = hits.getHits();
15         for (SearchHit searchHit : hits2) {
16             System.out.println(searchHit.getSourceAsString());
17         }
18     }
19     
20     
21     @Test
22     public void test17() throws Exception {
23         HashMap<String, Object> hashMap = new HashMap<String, Object>();
24         hashMap.put("name", "hello world");
25         hashMap.put("age", 20);
26         IndexResponse indexResponse = transportClient.prepareIndex(index, type, "7")
27                 .setSource(hashMap)
28                 .setRouting("heha")//指定一個路由參數,參數相同的數據會保存到同一個分片
29                 .get();
30         System.out.println(indexResponse.getVersion());
31     }
32     

 

 

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM