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依赖

    <properties>
        <!--指定ES版本-->
        <elasticsearch.version>6.4.0</elasticsearch.version>
    </properties>

<!--spring整合elasticsearch包 elasticsearch 因为springboot下的elasticsearch支持的版本是2.1 ,不能使用高版本的ES,比如6.4版本-->
        <!--<dependency>-->
        <!--<groupId>org.springframework.boot</groupId>-->
        <!--<artifactId>spring-boot-starter-data-elasticsearch</artifactId>-->
        <!--</dependency>-->

        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>transport</artifactId>
            <version>${elasticsearch.version}</version>
        </dependency>

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);
        }
    }

}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个简单的示例: 1. 引入依赖 在 pom.xml 文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> ``` 2. 配置 Elasticsearch 在 application.properties 文件中添加 Elasticsearch 相关配置: ```properties spring.elasticsearch.rest.uris=http://localhost:9200 ``` 3. 定义实体类 创建一个实体类,例如: ```java @Document(indexName = "user") public class User { @Id private String id; private String name; private Integer age; // getter/setter 略 } ``` 4. 创建 Elasticsearch Repository 创建一个继承自 ElasticsearchRepository 的接口,例如: ```java public interface UserRepository extends ElasticsearchRepository<User, String> { } ``` 5. 编写增删查改方法 在业务逻辑层中编写增删查改方法,例如: ```java @Service public class UserService { @Autowired private UserRepository userRepository; public void save(User user) { userRepository.save(user); } public void delete(String id) { userRepository.deleteById(id); } public List<User> search(String keyword) { return userRepository.findByNameContaining(keyword); } public void update(User user) { userRepository.save(user); } } ``` 以上示例中,save 方法用于保存用户信息,delete 方法用于删除用户信息,search 方法用于根据关键字搜索用户信息,update 方法用于更新用户信息。 6. 测试 编写测试类,例如: ```java @RunWith(SpringRunner.class) @SpringBootTest public class UserServiceTest { @Autowired private UserService userService; @Test public void testSave() { User user = new User(); user.setId("1"); user.setName("张三"); user.setAge(20); userService.save(user); } @Test public void testDelete() { userService.delete("1"); } @Test public void testSearch() { List<User> userList = userService.search("张三"); System.out.println(userList); } @Test public void testUpdate() { User user = new User(); user.setId("1"); user.setName("张三"); user.setAge(25); userService.update(user); } } ``` 以上示例中,testSave 方法用于测试保存用户信息,testDelete 方法用于测试删除用户信息,testSearch 方法用于测试根据关键字搜索用户信息,testUpdate 方法用于测试更新用户信息。 运行测试类,查看控制台输出结果,即可验证增删查改功能是否正常。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值