ElasticSearch6.4.0(四)数据操作 - 增删查改(JAVA API - TransportClient)

ES 配置文件说明:

        //9300端口: ES节点之间通讯使用
        //9200端口: ES节点 和 外部 通讯使用
        //(9300是tcp通讯端口,集群间和TCPClient都走的它;9200是http协议的RESTful接口)

tcp        0      0 0.0.0.0:9300            0.0.0.0:*               LISTEN      20330/java
tcp        0      0 0.0.0.0:9200            0.0.0.0:*               LISTEN      20330/java
discovery.zen.ping.unicast.hosts: ["Node1_IP:9300", "Node2_IP:9300", "Node3_IP:9300"]

导入pom依赖

    
        
        6.4.0
    


        
        
        
        

        
            org.elasticsearch.client
            transport
            ${elasticsearch.version}
        

ES配置类

package com.itcast.elasticsearch;/**
 * @author n00444323
 * @date 2019/2/20 11:21
 */

import org.elasticsearch.client.ElasticsearchClient;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.Transport;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;

/**
 * @param
 * @return
 * @throws
 */
@Configuration
public class ESConfig
{
    @Bean
    public TransportClient eSClient() throws UnknownHostException
    {
        //9300端口: ES节点之间通讯使用
        //9200端口: ES节点 和 外部 通讯使用
        //(9300是tcp通讯端口,集群间和TCPClient都走的它;9200是http协议的RESTful接口)
        TransportAddress address = new TransportAddress(InetAddress.getByName("192.168.135.128"), 9300);
        Settings settings = Settings.builder()
                .put("cluster.name", "elasticsearch")
                .build();
        TransportClient client = new PreBuiltTransportClient(settings);
        client.addTransportAddress(address);
        return client;
    }

}

 controller 添加  CRUD ES操作,具体可以查看博客https://blog.csdn.net/g1969119894/article/details/80169055#%E6%90%9C%E7%B4%A2%E5%85%A8%E9%83%A8

package com.itcast.controller

import com.itcast.auth.annotation.TokenAuthorization;
import com.itcast.http.httptemplete.CmasConfService;
import com.itcast.http.okhttp.service.OkHttpService;
import com.itcast.kafka.KafkaSender;
import com.itcast.logger.annotation.OpLog;
import com.itcast.logger.constants.OperateEnum;
import com.itcast.utils.TimeUtils;

import org.elasticsearch.action.delete.DeleteRequest;
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.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;
import java.util.concurrent.ExecutionException;

import javax.annotation.PostConstruct;

/**
 * @param
 * @return
 * @throws
 */
@RestController
public class MyController
{

    @Autowired
    OkHttpService okHttpService;

    @Autowired
    TransportClient eSClient;


   
    @RequestMapping("/people/man")
    public ResponseEntity elasticsearchQuery(@RequestParam(name = "id", defaultValue = "") String id)
    {
        GetResponse result = eSClient.prepareGet("people", "man", id)
                .get();
        return new ResponseEntity(result.getSource(), HttpStatus.OK);
    }

    @RequestMapping(value = "/add/people/man",
            method = RequestMethod.POST
    )
    public ResponseEntity elasticsearchAdd(@RequestParam(name = "name") String name,
                                           @RequestParam(name = "age") Integer age,
                                           @RequestParam(name = "country") String country,
                                           @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date date)
    {

        try
        {
            XContentBuilder content = XContentFactory.jsonBuilder()
                    .startObject()
                    .field("name", name)
                    .field("age", age)
                    .field("country", country)
                    .field("date", date)
                    .endObject();
            IndexResponse result = eSClient.prepareIndex("people", "man")
                    .setSource(content)
                    .get();
            return new ResponseEntity(result.getId(), HttpStatus.OK);
        }
        catch (IOException e)
        {
            e.printStackTrace();
            return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


    //修改ES索引数据
    @RequestMapping(value = "/modify/people/man",
            method = RequestMethod.PUT
    )
    public ResponseEntity modifyElasticsearch(@RequestParam(name = "id") String id,
                                              @RequestParam(name = "name", required = false) String name,
                                              @RequestParam(name = "age", required = false) Integer age,
                                              @RequestParam(name = "country", required = false) String country,
                                              @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date date)
    {

        try
        {
            XContentBuilder content = XContentFactory.jsonBuilder()
                    .startObject();
            content.field("name", name)
                    .field("age", age)
                    .field("country", country)
                    .field("date", date)
                    .endObject();
            UpdateResponse response = eSClient.prepareUpdate("people", "man", id)
                    .setDoc(content).get();
            return new ResponseEntity(response.getId(), HttpStatus.OK);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


    //删除ES索引数据
    @RequestMapping(value = "/delete/people/man",
            method = RequestMethod.DELETE
    )
    public ResponseEntity deleteElasticsearch(@RequestParam(name = "id") String id)
    {
        try
        {
            DeleteResponse response = eSClient.prepareDelete("people", "man", id).get();
            return new ResponseEntity(response.getId(), HttpStatus.OK);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

}

 

你可能感兴趣的:(ES)