【SpringBoot】Java Web-ElasticSearch简单示例

一、pom.xml依赖关系完整配置

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>elasticsearch</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>elasticsearch</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.83</version>
</dependency>
<!--elasticsearch-->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.10.0</version>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>

</project>

 

二、启动elasticsearch服务,参考:https://www.cnblogs.com/lightbc/p/17093646.html

 

三、编写配置类,客户端连接示例配置类。

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ElasticSearchConfig {
    private static final String HOST="127.0.0.1";
    private static final int PORT=9200;
    private static final String PROTOCOL="http";

    @Bean
    public RestHighLevelClient client(){
        HttpHost host=new HttpHost(HOST,PORT,PROTOCOL);
        RestClientBuilder builder= RestClient.builder(host);
        RestHighLevelClient client=new RestHighLevelClient(builder);
        return client;
    }

}

 

四、编写elasticsearch CRUD工具类

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;

import java.io.IOException;
import java.util.Map;
import java.util.UUID;

/**
* elasticsearch 工具处理类
*/
@Slf4j
public class ElasticSearchUtil {
private RestHighLevelClient client;
public ElasticSearchUtil(){
}
public ElasticSearchUtil(RestHighLevelClient client){
this.client=client;
}
/**
* 新增数据
* @param index 索引
* @param data 数据
* @return boolean 成功:true,失败:false
*/
public boolean add(String index,String data){
boolean b=false;
try {
IndexRequest request=new IndexRequest(index);
String uuid= UUID.randomUUID().toString().replaceAll("-","");
request.id(uuid);
log.warn("设置ES数据文档索引id成功,id:{}",uuid);
request.source(JSONObject.parseObject(data));
IndexResponse response=client.index(request, RequestOptions.DEFAULT);
if(response!=null){
RestStatus status=response.status();
log.warn("ES新增索引响应状态:{}",status);
if(status==RestStatus.CREATED){
b=true;
log.warn("创建成功!");
}
}
} catch (Exception e) {
log.error("ES新增索引报错:{}",e.getMessage());
}finally {
return b;
}
}

/**
* 删除数据
* @param index 索引
* @param id id
* @return boolean 成功:true,失败:false
*/
public boolean delete(String index,String id){
boolean b=false;
try {
DeleteRequest request=new DeleteRequest(index,id);
DeleteResponse response=client.delete(request,RequestOptions.DEFAULT);
if(response!=null){
RestStatus status=response.status();
log.warn("ES删除索引响应状态:{}",status);
if(status==RestStatus.OK){
b=true;
log.warn("删除成功!");
}
}
} catch (Exception e) {
log.error("ES删除索引报错:{}",e.getMessage());
}finally {
return b;
}
}

/**
* 更新数据
* @param index 索引
* @param id id
* @param data 数据
* @return boolean 成功:true,失败:false
*/
public boolean update(String index,String id,String data){
boolean b=false;
try {
UpdateRequest request=new UpdateRequest(index,id);
request.doc(JSONObject.parseObject(data));
UpdateResponse response=client.update(request,RequestOptions.DEFAULT);
if(response!=null){
RestStatus status=response.status();
log.warn("ES更新索引响应状态:{}",status);
if(status==RestStatus.OK){
b=true;
log.warn("更新成功!");
}
}
} catch (Exception e) {
log.error("ES更新索引报错:{}",e.getMessage());
}finally {
return b;
}
}

/**
* 查询数据
* @param index 索引
* @param from 开始位置
* @param size 查询条数
* @param kw 查询关键字
*/
public JSONObject search(String index, int from, int size, String kw){
JSONObject json=new JSONObject();
try {
SearchRequest request=new SearchRequest(index);
SearchSourceBuilder searchSourceBuilder=new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchQuery("kw",kw))
.from(from)
.size(size)
.postFilter(QueryBuilders.matchQuery("kw",kw));
HighlightBuilder highlightBuilder=new HighlightBuilder();
String preTags="<em>";
String postTags="</em>";
highlightBuilder.preTags(preTags)
.postTags(postTags)
.field("kw");
searchSourceBuilder.highlighter(highlightBuilder);
request.source(searchSourceBuilder);
SearchResponse response=client.search(request,RequestOptions.DEFAULT);
if(response!=null){
RestStatus status=response.status();
log.info("ES查询数据响应状态:{}",status);
log.info("符合查询条件的查询文档总数:{}",response.getHits().getTotalHits());
SearchHit[] hits=response.getHits().getHits();
StringBuilder builder=new StringBuilder();
for(SearchHit hit:hits){
Map<String, HighlightField>fields=hit.getHighlightFields();
HighlightField field=fields.get("kw");
if(field!=null){
Text[] texts=field.getFragments();
for(Text text:texts){
builder.append(text);
}
}
}
json.put("highLight",builder.toString());
}
} catch (IOException e) {
log.error("ES查询数据I0异常:{}",e.getMessage());
}catch (Exception e){
log.error("ES查询报错:{}",e.getMessage());
}finally {
return json;
}
}
}

 

五、编写elasticsearchCRUD测试控制器类

import com.alibaba.fastjson.JSONObject;
import com.example.elasticsearch.util.ElasticSearchUtil;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("s")
public class SearchController {
    @Autowired
    private RestHighLevelClient client;

    /**
     * 新增数据
     * @param index 索引
     * @param data 数据
     * @return string 是否新增成功描述信息
     */
    @PostMapping(value = "add")
    public String add(String index,String data){
        String desc="新增失败!";
        ElasticSearchUtil util=new ElasticSearchUtil(client);
        boolean b=util.add(index,data);
        if(b){
            desc="新增成功!";
        }
        return desc;
    }

    /**
     * 删除数据
     * @param index 索引
     * @param id id
     * @return string 是否删除成功描述信息
     */
    @GetMapping(value = "/d/{index}/{id}")
    public String delete(@PathVariable("index") String index,@PathVariable("id") String id){
        String desc="删除失败!";
        ElasticSearchUtil util=new ElasticSearchUtil(client);
        boolean b=util.delete(index,id);
        if(b){
            desc="删除成功!";
        }
        return desc;
    }

    /**
     * 更新数据
     * @param index 索引
     * @param id id
     * @param data 数据
     * @return string 是否更新成功描述信息
     */
    @PostMapping(value = "u")
    public String update(String index,String id,String data){
        String desc="更新失败!";
        ElasticSearchUtil util=new ElasticSearchUtil(client);
        boolean b=util.update(index,id,data);
        if(b){
            desc="更新成功!";
        }
        return desc;
    }

    /**
     * 查询数据
     * @param index 索引
     * @param from 查询起始位置
     * @param size 查询条数
     * @param kw 查询关键字
     * @return SearchHits 匹配记录数
     */
    @GetMapping(value = "/q")
    public JSONObject search(@RequestParam("index") String index, @RequestParam("from") int from, @RequestParam("size") int size, @RequestParam("kw") String kw){
        ElasticSearchUtil util=new ElasticSearchUtil(client);
        return util.search(index, from, size, kw);
    }
}

 

六、运行测试

6.1、新增

 

 

 

 

 

 

 

 

6.2、修改

 

 

 

 

 

 

 

6.3、查询

 

 

6.4、删除

 

 

 

posted @ 2023-03-05 22:20  lightbc  阅读(59)  评论(0编辑  收藏  举报