Java操作Elasticsearch

来源:互联网 发布:msqrd软件安卓版 编辑:程序博客网 时间:2024/05/17 05:59
ava操作Elasticsearch


今天呢,发一篇JAVA操作ES搜索引擎的代码吧!


创建工程就不说了

Maven工程:加入Maven依赖!!!

pom.xml

[html] view plain copy
  1. <dependency>  
  2.         <groupId>junit</groupId>  
  3.         <artifactId>junit</artifactId>  
  4.         <version>4.12</version>  
  5.         <scope>test</scope>  
  6.     </dependency>  
  7.     <dependency>  
  8.         <groupId>org.elasticsearch</groupId>  
  9.         <artifactId>elasticsearch</artifactId>  
  10.         <version>1.4.4</version>  
  11.     </dependency>  
  12.     <dependency>  
  13.         <groupId>com.fasterxml.jackson.core</groupId>  
  14.         <artifactId>jackson-databind</artifactId>  
  15.         <version>2.1.3</version>  
  16.     </dependency>  

JUnit测试首先连接:

[java] view plain copy
  1. /** 
  2.  * Title: testConnection 
  3.  * Description: 测试连接 
  4.  */  
  5. TransportClient client = null;  
  6. @Before  
  7. public void connection(){  
  8.     //设置一些属性  
  9.     //Settings settings = ImmutableSettings.settingsBuilder().put("cluster.name","elasticsearch").build();  
  10.     // 获取一个客户端对象  
  11.     client = new TransportClient();//new TransportClient(settings);  
  12.     //  指定连接的Es节点Ip和端口 端口默认使用 9300  
  13.     TransportAddress transportAddress = new InetSocketTransportAddress("cloudera",9300);  
  14.     client.addTransportAddress(transportAddress);  
  15.     //  获取客户端 连接上的节点信息  
  16.     ImmutableList<DiscoveryNode> nodes = client.connectedNodes();  
  17.     for (DiscoveryNode discoveryNode : nodes) {  
  18.         System.out.println(discoveryNode.getHostAddress()+"\t"+discoveryNode.getHostName());  
  19.     }  
  20.       
  21. }  
上面用到的核心类:TransportClient


定义两个常量 方便之后的操作:

[java] view plain copy
  1. private final static String INDEX = "test";  
  2. private final static String TYPE = "emp";  
  3.       

上面是索引库的位置 和 类型

  

创建索引:有4种方法 下面给出代码

[java] view plain copy
  1. /** 
  2.  *  
  3.  * Title: creatIndex1 
  4.  * Description:创建索引___JSON 
  5.  */  
  6. @Test  
  7. public void creatIndex1() {  
  8.     String jsonstr = "{\"name\":\"Baby\",\"address\":\"jx\",\"age\":23}";  
  9.       
  10.     IndexResponse response = client.prepareIndex(INDEX, TYPE, "3")//  
  11.             .setSource(jsonstr).execute()//  
  12.             .actionGet();  
  13.       
  14.     System.out.println(response.getId());  
  15. }  
  16.   
  17.   
  18. /** 
  19.  *  
  20.  * Title: creatIndex2 
  21.  * Description:创建索引___Map 
  22.  */  
  23. @Test  
  24. public void creatIndex2() {  
  25.     Map<String, Object> source = new HashMap<String, Object>();  
  26.     source.put("name""ww");  
  27.     source.put("age"20);  
  28.     source.put("address""SH");  
  29.       
  30.       
  31.     IndexResponse response = client.prepareIndex(INDEX, TYPE)//  
  32.             .setSource(source).execute()//  
  33.             .actionGet();  
  34.     System.out.println(response.getId());  
  35. }  
  36.   
  37.   
  38. /** 
  39.  *  
  40.  * Title: creatIndex3 
  41.  * Description:创建索引___Bean-->工具类转JSON 
  42.  * @throws JsonProcessingException  
  43.  */  
  44. @Test  
  45. public void creatIndex3() throws Exception {  
  46.       
  47.     Person person = new Person();  
  48.     person.setName("JSQ");  
  49.     person.setAge(21);  
  50.     person.setAddress("JL");  
  51.       
  52.     ObjectMapper mapper = new ObjectMapper();  
  53.       
  54.     IndexResponse response = client.prepareIndex(INDEX, TYPE)//  
  55.             .setSource(mapper.writeValueAsString(person)).execute()//  
  56.             .actionGet();  
  57.     System.out.println(response.getId());  
  58. }  
  59.   
  60. /** 
  61.  *  
  62.  * Title: creatIndex4  
  63.  * Description:创建索引___工具类 XContentBuilder 
  64.  * @throws JsonProcessingException  
  65.  */  
  66. @Test  
  67. public void creatIndex4() throws Exception {  
  68.       
  69.     XContentBuilder builder = XContentFactory.jsonBuilder()//  
  70.             .startObject()//  {  
  71.             .field("name""test")// "name":"test"  
  72.             .field("age"31)//  
  73.             .endObject();//  }  
  74.       
  75.     IndexResponse response = client.prepareIndex(INDEX, TYPE)//  
  76.             .setSource(builder).execute()//  
  77.             .actionGet();  
  78.     System.out.println(response.getId());  
  79. }  

根据ID读取索引

[java] view plain copy
  1. /** 
  2.      *  
  3.      * Title: getIndex 
  4.      * Description:查詢 
  5.      */  
  6.     @Test  
  7.     public void getIndexByID(){  
  8.      GetResponse get = client.prepareGet(INDEX, TYPE, "1").execute().actionGet();  
  9.        
  10.      System.out.println(get.getSourceAsString());  
  11.           
  12.     }  


更新操作:

[java] view plain copy
  1. /** 
  2.      *  
  3.      * Title: getIndex 
  4.      * Description:更新1 
  5.      * @throws IOException  
  6.      */  
  7.     @Test  
  8.     public void Update() throws Exception {  
  9.         XContentBuilder builder = XContentFactory.jsonBuilder()//  
  10.                 .startObject()//  {  
  11.                 .field("name""qwer")// "name":"test"  
  12.                 .field("age"16)//  
  13.                 .endObject();//  }  
  14.           
  15.           
  16.         UpdateResponse response = client.prepareUpdate(INDEX, TYPE, "AVZ_sjFPSKhvuiHi4K8Z").setDoc(builder).execute().actionGet();  
  17.   
  18.         System.out.println(response.getVersion());  
  19.           
  20.     }  
  21.       
  22.     /** 
  23.      *  
  24.      * Title: getIndex  
  25.      * Description:更新2 
  26.      *  
  27.      * @throws Exception 
  28.      */  
  29.     @Test  
  30.     public void Update2() throws Exception {  
  31.         UpdateRequest request = new UpdateRequest(INDEX, TYPE, "AVZ_sjG3SKhvuiHi4K8a");  
  32.         request.doc(XContentFactory.jsonBuilder().startObject().field("age"18).endObject());  
  33.         UpdateResponse response = client.update(request).get();  
  34.         System.out.println(response.getVersion());  
  35.     }  
  36.       
  37.     /** 
  38.      *  
  39.      * Title: UpdateOrCreate 
  40.      * Description: 更新或者插入 
  41.      * @throws Exception 
  42.      */  
  43.     @Test  
  44.     public void UpdateOrCreate() throws Exception {  
  45.     UpdateRequest request = new UpdateRequest(INDEX, TYPE, "4");  
  46.     XContentBuilder builder = XContentFactory.jsonBuilder()//  
  47.             .startObject()//  {  
  48.             .field("name""adfg")// "name":"test"  
  49.             .field("age"66)//  
  50.             .endObject();//  }  
  51.       
  52.     request.doc(builder);  
  53.       
  54.     request.upsert(builder);  
  55.       
  56.     UpdateResponse response = client.update(request).get();  
  57.     System.out.println(response.getVersion());  
  58.     }  
  59.       


删除操作
[java] view plain copy
  1. /** 
  2.      *  
  3.      * Title: UpdateOrCreate 
  4.      * Description: 删除1 
  5.      * @throws Exception 
  6.      */  
  7.     @Test  
  8.     public void delete() throws Exception {  
  9.         DeleteRequest request = new DeleteRequest(INDEX, TYPE, "AVZ9SoaeqXbhzyjETmWC");  
  10.           
  11.         DeleteResponse response = client.delete(request ).get();  
  12.           
  13.         System.out.println("版本:"+response.getVersion());  
  14.     }  
  15.       
  16.       
  17.       
  18.     /** 
  19.      *  
  20.      * Title: UpdateOrCreate 
  21.      * Description: 删除2 
  22.      * @throws Exception 
  23.      */  
  24.     @Test  
  25.     public void delete2() throws Exception {  
  26.         DeleteResponse response = client.prepareDelete(INDEX, TYPE, "1").execute().actionGet();  
  27.           
  28.         System.out.println("版本:"+response.getVersion());  
  29.     }  


求索引总数:
[java] view plain copy
  1. /** 
  2.  *  
  3.  * Title: QueryCount 
  4.  * Description: 求总数 
  5.  * @throws Exception 
  6.  */  
  7. @Test  
  8. public void QueryCount() throws Exception {  
  9.     long l = client.prepareCount(INDEX).execute().get().getCount();  
  10.     System.out.println("总数:"+l);  
  11. }  

批量操作:
[java] view plain copy
  1. /** 
  2.  *  
  3.  * Title: testBulk 
  4.  * Description:批量操作 
  5.  */  
  6. @Test  
  7. public void testBulk(){  
  8.     BulkRequestBuilder bulk = client.prepareBulk();  
  9.       
  10.     //创建索引  
  11.     IndexRequest request1 = new IndexRequest(INDEX, TYPE, "101");  
  12.     request1.source("{\"name\":\"test101\",\"age\":101}");  
  13.     IndexRequest request2 = new IndexRequest(INDEX, TYPE, "102");  
  14.     request2.source("{\"name\":\"test102\",\"age\":102}");  
  15.       
  16.     //删除索引  
  17.     DeleteRequest request3 = new DeleteRequest(INDEX, TYPE, "2");  
  18.       
  19.     bulk.add(request1);  
  20.     bulk.add(request2);  
  21.     bulk.add(request3);  
  22.       
  23.     BulkResponse response = bulk.execute().actionGet();  
  24.       
  25.     if(response.hasFailures()){  
  26.         System.out.println("发生错误");  
  27.     }else{  
  28.         System.out.println("全部执行成功");  
  29.     }  
  30. }  



代码也比较简单 很好理解!!!
原创粉丝点击