Elasticsearch系列(七)--JAVA调用

1.创建maven项目,pom.xml文件中增加如下配置:

<dependencies>
    <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>transport</artifactId>
        <version>6.4.0</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.2</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
                <encoding>UTF-8</encoding>
            </configuration>
        </plugin>
    </plugins>
</build>

java代码调用:

package com.es.elasticsearch;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
import net.sf.json.JSONObject;
 
import java.io.IOException;
import java.net.InetAddress;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
 
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
 
public class ElasticsearchTest_1 {
 
  private Logger logger = LoggerFactory.getLogger(ElasticsearchTest_1.class);
  
  public final static String HOST="127.0.0.1";
  
  //http请求的端口是9200,客户端是9300
  public final static int PORT = 9300; 
  
  public final static String CLUSTERNAME = "elasticsearch";
  
  public static TransportClient getConnection() throws Exception {
       
       Settings settings = Settings.builder()
                      .put("client.transport.sniff", true) //增加嗅探机制,找到ES集群
                      .put("cluster.name", CLUSTERNAME)  // 设置集群名称
                      .put("thread_pool.search.size", 20)// 增加线程池个数,暂时设为20
                          .build();
        // 创建client
       TransportClient client = new PreBuiltTransportClient(settings)
                                .addTransportAddresses(new TransportAddress(InetAddress.getByName(HOST), PORT));
        
        return client;
    }
  
    /*
     * 添加
     * 索引和类型是必需的,而id部分是可选的。如果不指定ID,ElasticSearch会为我们生成一个ID。 
    */  
  public void add() throws Exception{
    try {
      XContentBuilder content = XContentFactory.jsonBuilder().startObject()
                            .field("name","daniel")
                            .field("age",20)
                            .field("job","coder")
                            .endObject();
      
      String index = "data";   // 索引值
      String type ="person";   // 类型
      String id="1";           // id值
      TransportClient client = this.getConnection();
      IndexResponse iresp = client.prepareIndex(index, type,id).setSource(content).get();
      client.close();
      
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    
  }
  /*
   * 添加索引:传入json字符串
   * id 自动创建
   * 
   * */
  public void addJsonstr() throws Exception{
    String jsonstr = "{\"userName\":\"Tom\",\"date\":\"2018-11-7\",\"msg\":\"where are you\"}";
    TransportClient client = this.getConnection();
    IndexResponse iresp = client.prepareIndex("chat", "msg").setSource(jsonstr,XContentType.JSON).get();
    client.close();
    System.err.println(iresp.getIndex());
    System.err.println(iresp.getId());
    System.out.println(iresp.status());
    
  }
  
  /*
   * 添加索引:传入json
   * 
   * */
  public void addJSON() throws Exception{
    
    JSONObject json = new JSONObject();
    json.put("userName", "allen");
    json.put("date", new Date().toString());
    json.put("msg", "hello  allen");
    
    TransportClient client = this.getConnection();
    IndexResponse iresp = client.prepareIndex("chat", "msg","3").setSource(json,XContentType.JSON).get();
    
    client.close();
    System.err.println(iresp.getIndex());
    System.err.println(iresp.getId());
    System.out.println(iresp.status());
    
  }
  
  /*
   * 创建索引-传入Map对象
   * 
   * */
  public void addMap() throws Exception{
     Map<String, Object> map = new HashMap<String,Object>();
              map.put("userName", "Daniel");
              map.put("sendDate", new Date());
              map.put("msg", "hello Daniel");
              
      TransportClient client = this.getConnection();
      IndexResponse response = client.prepareIndex("momo", "msg","1").setSource(map).get();
              
              logger.info("map索引名称:" + response.getIndex() + "\n map类型:" + response.getType()
             + "\n map文档ID:" + response.getId() + "\n当前实例map状态:" + response.status());
              
         }
  
    /*  
     * 获取数据
    */  
  public void get(String index,String type,String id) throws Exception{
    TransportClient client = this.getConnection();
    GetResponse  result = client.prepareGet(index,type,id).get();
    System.out.println(result.getSourceAsString());
    System.out.println(result.getType());
    System.out.println(result.getVersion());
    System.err.println(result.getIndex());
    System.err.println(result.getId());
    
    client.close();
  }
  
  /*  
   * 更新
  */  
  public void update() throws Exception{
    XContentBuilder content = XContentFactory.jsonBuilder().startObject();
    content.field("age",22);
    content.field("job","boss");
    content.endObject();
    UpdateRequest request = new UpdateRequest("data","person","1");
    request.doc(content);
    TransportClient client = this.getConnection();
    UpdateResponse resp = client.update(request).get();
    client.close();
  }
  
  /*  
   * 删除
  */  
  public void delete() throws Exception{
    TransportClient client = this.getConnection();
    DeleteResponse  response = client.prepareDelete("data","person","1").get();
    client.close();
    System.out.println(response.getResult());
  }
  
  /*  
   * 关闭
  */  
  public static void closeConnect(TransportClient client){
    if(null !=client){
      client.close();
    }
  }
  
  
  public static void main(String[] args) throws Exception {
    /*TransportClient  client = getConnection();
    System.out.println(client.toString());
    System.out.println(client.nodeName());*/
    
    ElasticsearchTest_1 t = new ElasticsearchTest_1();
    
//      t.add();
//    t.get();
    
//    t.update();
//    t.get();
    
//    t.delete();
//    t.get("data","person","1");
    
//    t.addJsonstr();
//    t.get("chat", "msg","5jbh7GYB_P4tFfCC1ruQ");
//    t.get("chat", "msg","5zbl7GYB_P4tFfCCpLt1");
    
//    t.addJSON();
    t.get("chat", "msg","3");
    
//    t.addMap();
//    t.get("momo", "msg","1");
  }
  
}

请关注我微信公众号:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值