elasticsearch整合springboot实现增删改查

<properties>
        <elasticsearch.version>6.7.1</elasticsearch.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>transport</artifactId>
            <version>${elasticsearch.version}</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.plugin</groupId>
            <artifactId>transport-netty4-client</artifactId>
            <version>6.7.1</version>
        </dependency>
package com.stylefeng.guns.modular.es;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

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

@Configuration
public class ESConfig {
    private static String clusterName="my-application";
    private static String host="****";
    private static Integer port=9300;


    /** 构建Settings 对象 */
    private static Settings settings = Settings.builder().put("cluster.name", clusterName).build();
    /** TransportClient 对象, 用于连接ES集群 */
    private static volatile TransportClient client;

    /**
     * 同步synchronized(*.class)代码块的作用和synchronized static方法作用一样,
     * 对当前对应的*.class 进行持锁, static方法和.class 一样都是锁的该类本身,同一个监听器
     * @return
     */
    @Bean
    public static TransportClient getClient(){
        if(client == null){
            synchronized (TransportClient.class){
                client = new PreBuiltTransportClient(settings);
                try {
                    String[] allHost = host.split(",");
                    for (String str:allHost) {
                        client.addTransportAddresses(new TransportAddress(InetAddress.getByName(str), port));
                    }
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
            }
        }
        return client;
    }

}

package com.stylefeng.guns.modular.es;

import org.apache.ibatis.annotations.Delete;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
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.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

@RestController
public class ESController {
    @Autowired
    private TransportClient client;
    @GetMapping("/get/people/man")
    public ResponseEntity get(@RequestParam(name="id",defaultValue = "") String id){
        if(id.isEmpty()){
            return new ResponseEntity( HttpStatus.NOT_FOUND);
        }
        GetResponse response=this.client.prepareGet("people","man",id).get();
        if(!response.isExists()){
            return new ResponseEntity(response.getSource(), HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity(response.getSource(), HttpStatus.OK);
    }

    /**
     * @param date
     * @param country
     * @param name
     * @param age
     * @return
     */

    @RequestMapping("/add/people/man")
    @ResponseBody
    public ResponseEntity add(  @RequestParam(value = "date") String date,
                                    @RequestParam(value = "country") String country,
                                     @RequestParam(value = "name") String name,
                                     @RequestParam(value = "age") int age
                              ){
        System.out.println("date.toString()+country+name+age"+date+country+name+age);
        try{
            XContentBuilder contentBuilder=XContentFactory.jsonBuilder().startObject()
                    .field("date",date)
                    .field("country",country)
                    .field("name",name)
                    .field("age",age)
                    .endObject();
            IndexResponse response=this.client.prepareIndex("people","man").setSource(contentBuilder).get();
            return new ResponseEntity(response.getId(),HttpStatus.OK);
        }catch (IOException e){
            e.printStackTrace();
            return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @RequestMapping("/delete/people/man")
    public ResponseEntity delete(String id){
        DeleteResponse deleteResponse=this.client.prepareDelete("people","man",id).get();
        return new ResponseEntity(deleteResponse.getResult().toString(),HttpStatus.OK);
    }

    @RequestMapping("/update/people/man")
    public ResponseEntity update(@RequestParam String id,

                                 @RequestParam(value = "country",required = false) String country,
                                 @RequestParam(value = "name",required = false) String name
                                 ){
        UpdateRequest updateRequest=new UpdateRequest("people","man",id);
        try {
            XContentBuilder builder=XContentFactory.jsonBuilder().startObject();
            if(name!=null){
                builder.field("name",name);
            }
            if(country!=null){
                builder.field("country",country);
            }
            builder.endObject();
            updateRequest.doc(builder);
        }catch (IOException e){
            e.printStackTrace();
            return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
        }
        try {
            UpdateResponse updateResponse=this.client.update(updateRequest).get();
            return new ResponseEntity(updateResponse.getResult().toString(),HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    @PostMapping("/query/people/man")
    public ResponseEntity query(@RequestParam(name = "name",required = false)String name,
                                @RequestParam(name = "country",required = false)String country,
                                @RequestParam(name = "gt_word_count",defaultValue = "0")int gtWordCount,
                                @RequestParam(name = "lt_word_count",required = false)Integer ltWordCount){
        BoolQueryBuilder boolQueryBuilder=QueryBuilders.boolQuery();
        if(name!=null){
            boolQueryBuilder.must(QueryBuilders.matchQuery("name",name));
        }
        if(country!=null){
            boolQueryBuilder.must(QueryBuilders.matchQuery("country",country));

        }
        RangeQueryBuilder rangeQueryBuilder=QueryBuilders.rangeQuery("word_count").from(gtWordCount);
        if(ltWordCount!=null&&ltWordCount>0){
            rangeQueryBuilder.to(ltWordCount);
        }boolQueryBuilder.filter(rangeQueryBuilder);
        SearchRequestBuilder searchRequestBuilder=this.client.prepareSearch("people").setTypes("man").setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                .setQuery(boolQueryBuilder).setFrom(0).setSize(10);
        SearchResponse response=searchRequestBuilder.get();
        List<Map<String,Object>> result=new ArrayList<>();
        for (SearchHit h :response.getHits()) {
            result.add(h.getSourceAsMap());
        }
        return new ResponseEntity(result,HttpStatus.OK);
    }
}

你可以按照以下步骤使用 Spring Boot 和 Elasticsearch 实现增删改查的功能: 1. 添加依赖:在你的 Spring Boot 项目的 pom.xml 文件中,添加 Elasticsearch 相关的依赖。例如: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> ``` 2. 配置 Elasticsearch:在你的 application.properties 或 application.yml 文件中,配置 Elasticsearch 的连接信息。例如: ```yaml spring.data.elasticsearch.cluster-nodes=localhost:9200 ``` 3. 创建实体类:创建一个代表你要操作的数据的实体类,并使用注解来映射到 Elasticsearch 中的索引和类型。例如: ```java import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; @Document(indexName = "your_index_name", type = "your_type_name") public class YourEntity { @Id private String id; private String name; // 其他属性和方法 } ``` 4. 创建数据访问接口:创建一个继承自 ElasticsearchRepository 的数据访问接口,该接口提供了一些基本的 CRUD 方法。例如: ```java import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; public interface YourEntityRepository extends ElasticsearchRepository<YourEntity, String> { // 可以根据需要添加自定义的查询方法 } ``` 5. 编写业务逻辑:在你的服务类中使用 YourEntityRepository 来进行相关的数据操作。例如: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class YourService { @Autowired private YourEntityRepository repository; public YourEntity save(YourEntity entity) { return repository.save(entity); } public void delete(String id) { repository.deleteById(id); } public Iterable<YourEntity> findAll() { return repository.findAll(); } // 可以根据需要添加其他的查询方法和业务逻辑 } ``` 这样,你就可以通过调用 YourService 中的方法来实现Elasticsearch增删改查操作了。希望对你有帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值