Java之Elasticsearch 增刪改查

來源:互聯網
上載者:User

標籤:ota   factory   track   termquery   sdn   format   for   order   ram   

<!--ELK  --><dependency>   <groupId>org.elasticsearch.client</groupId>   <artifactId>transport</artifactId>   <version>5.1.1</version>   <exclusions>      <!--<exclusion>         <artifactId>transport-netty4-client</artifactId>         <groupId>org.elasticsearch.plugin</groupId>      </exclusion>-->   </exclusions></dependency><dependency>   <groupId>org.apache.logging.log4j</groupId>   <artifactId>log4j-core</artifactId>   <version>2.6.2</version></dependency><!-- springmvc json --><dependency>   <groupId>com.fasterxml.jackson.core</groupId>   <artifactId>jackson-databind</artifactId>   <version>2.8.8</version></dependency><dependency>   <groupId>org.codehaus.jackson</groupId>   <artifactId>jackson-mapper-asl</artifactId>   <version>1.9.13</version></dependency><dependency>   <groupId>com.fasterxml.jackson.core</groupId>   <artifactId>jackson-core</artifactId>   <version>2.8.8</version></dependency><dependency>   <groupId>com.fasterxml.jackson.core</groupId>   <artifactId>jackson-annotations</artifactId>   <version>2.8.5</version></dependency>


 

 
package com.sxis.util;
import java.io.IOException;import java.net.InetAddress;import java.net.UnknownHostException;import java.util.Date;import java.util.HashMap;import java.util.Map;import java.util.concurrent.ExecutionException;import org.elasticsearch.ElasticsearchException;import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse;import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;import org.elasticsearch.action.delete.DeleteResponse;import org.elasticsearch.action.get.GetResponse;import org.elasticsearch.action.index.IndexResponse;import org.elasticsearch.action.search.SearchResponse;import org.elasticsearch.action.search.SearchType;import org.elasticsearch.client.transport.TransportClient;import org.elasticsearch.common.settings.Settings;import org.elasticsearch.common.transport.InetSocketTransportAddress;import org.elasticsearch.common.xcontent.XContentBuilder;import org.elasticsearch.common.xcontent.XContentFactory;import org.elasticsearch.index.query.QueryBuilder;import org.elasticsearch.index.query.QueryBuilders;import org.elasticsearch.search.SearchHit;import org.elasticsearch.search.SearchHits;import org.elasticsearch.search.sort.SortOrder;import org.elasticsearch.transport.client.PreBuiltTransportClient;/**  * 【描述】:  ELK java API 介面 ,包括查詢,刪除,插入等待  * 【步驟】:       * @param* @return    * @throws       * @author    Allen  * @date      2017/7/4 9:47  */public class ElasticsearchUtil {   private static TransportClient client;   private static String elasticIp = "192.168.211.50";   private static int elasticPort = 9300;   /**     * 【描述】:  初始化Elasticsearch對象     * 【步驟】:     * @param* @return* @throws* @author    Allen     * @date      2017/7/4 15:19     */public static void init() throws UnknownHostException, InterruptedException, ExecutionException {      //設定ES執行個體的名稱.put("client.transport.sniff", true) //自動嗅探整個叢集的狀態,把叢集中其他ES節點的ip添加到本地的用戶端列表中      Settings esSettings = Settings.builder().put("cluster.name", "elasticsearch").build();      client = new PreBuiltTransportClient(esSettings);//初始化client較老版本發生了變化,此方法有幾個重載方法,初始化外掛程式等。      //此步驟添加IP,至少一個,其實一個就夠了,因為添加了自動嗅探配置      client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(elasticIp), elasticPort));      System.out.println("串連建立成功");   }   /**     * 【描述】:  建立index,把其中的文檔轉化為json的格式儲存     * 【步驟】:     * @param       <Node>:節點ip <port>:節點連接埠號碼,預設9200 <Index>:索引名 <Type>:索引類型 <ID>:操作對象的ID號    * @return* @throws* @author    Allen     * @date      2017/7/5 9:42     */public static void createIndex() throws ElasticsearchException,IOException {      for (int i=300; i<=50000000;i++){         User user = new User();         user.setId(1);         user.setName("huang fox " + i);         user.setAge(i % 100);         IndexResponse indexResponse = null;         indexResponse = client.prepareIndex("users", "user",i+"").setSource(generateJson(user)).execute().actionGet();         System.out.println("responseIsCreated: "+indexResponse);      }      System.out.println("it is ok !");   }   public static void query() throws Exception {      //term查詢      //QueryBuilder queryBuilder = QueryBuilders.termQuery("age", 50) ;  //年齡等於50      //range查詢      QueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("age").gt(50); //年齡大於50      SearchResponse searchResponse = client.prepareSearch("users")            .setTypes("user")            .setQuery(rangeQueryBuilder)     //query            .setPostFilter(QueryBuilders.rangeQuery( "age" ).from( 70 ).to( 80 )) // Filter            .addSort("age", SortOrder.DESC)            .setSize(120)   // 不設定的話,預設取10條資料            .execute().actionGet();      SearchHits hits = searchResponse.getHits();      System.out.println("查到記錄數:"+hits.getTotalHits());      SearchHit[] searchHists = hits.getHits();      if(searchHists.length>0){         for(SearchHit hit:searchHists){            String name =  (String) hit.getSource().get("name");            Integer age = Integer.parseInt( hit.getSource().get("age").toString() );            System.out.format("name:%s ,age :%d \n",name ,age);         }      }   }   /**    * 轉換成json對象    *    * @param user* @return*/private static String generateJson(User user) {      String json = "";      try {         XContentBuilder contentBuilder = XContentFactory.jsonBuilder().startObject();         contentBuilder.field("id", user.getId());         contentBuilder.field("name", user.getName());         contentBuilder.field("age", user.getAge());         json = contentBuilder.endObject().string();      } catch (IOException e) {         e.printStackTrace();      }      return json;   }   /*    * Get index 擷取文檔相當於讀取資料庫的一行資料    */   public static void getIndex(){      GetResponse getresponse = client.prepareGet("users", "user", "402").execute().actionGet();      System.out.println(getresponse.getSourceAsString());   }   /*    *Delete index 相當於刪除一行資料    */   public static void delete(){      DeleteResponse deleteresponse = client.prepareDelete("users", "user","1").execute().actionGet();      System.out.println(deleteresponse.getVersion());   }   /*    *Delete index 刪除索引及該索引所管轄的記錄    */   public static void deleteIndex(){      //刪除所有記錄      DeleteIndexResponse deleteIndexResponse = client.admin().indices().prepareDelete("logs").execute().actionGet();      System.out.println(deleteIndexResponse.isAcknowledged());   }   /**     * 【描述】:     擷取到所有的索引     * 【步驟】:     * @param* @return* @throws* @author    Allen     * @date      2017/7/4 16:27     */public static void getAllIndex(){      ClusterStateResponse response = client.admin().cluster().prepareState().execute().actionGet();      //擷取所有索引      String[] indexs=response.getState().getMetaData().getConcreteAllIndices();      for (String index : indexs) {         System.out.println( index + " delete" );//      }   }   public void close(){      //on shutdown 斷開叢集      client.close();   }   public static void main( String[] args ) {      try {         init();         //createIndex();         //getIndex();         //delete();         //deleteIndex();         //getAllIndex();         query();      } catch( Exception e ) {         e.printStackTrace();      }   }}class User{   private static final long serialVersionUID = 5290251719938640641L;   private Integer id;   private String name;   private int age;   public Integer getId() {      return id;   }   public void setId( Integer id ) {      this.id = id;   }   public String getName() {      return name;   }   public void setName( String name ) {      this.name = name;   }   public int getAge() {      return age;   }   public void setAge( int age ) {      this.age = age;   }}
 

Java之Elasticsearch 增刪改查

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.