SpringBoot 整合ElasticSearch实现模糊查询,批量CRUD,排序,分页,高亮

这篇具有很好参考价值的文章主要介绍了SpringBoot 整合ElasticSearch实现模糊查询,批量CRUD,排序,分页,高亮。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

准备工作

准备一个空的SpringBoot项目

写入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

注意你的SpringBoot和你的es版本,一定要对应,如果不知道的可以查看这篇文章:https://blog.csdn.net/u014641168/article/details/130386872

我的版本是2.2.6,所以用的ES版本是 6.8.12,安装es请看这篇文章:https://blog.csdn.net/u014641168/article/details/130622430
SpringBoot 整合ElasticSearch实现模糊查询,批量CRUD,排序,分页,高亮
查看ES版本
SpringBoot 整合ElasticSearch实现模糊查询,批量CRUD,排序,分页,高亮
SpringBoot 整合ElasticSearch实现模糊查询,批量CRUD,排序,分页,高亮

配置

创建ES配置文件,下面有2个Bean,一个是你的ES有账号密码的,另一个默认是没有的。

package cn.ityao.es.config;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Author tongyao
 */
@Configuration
public class ElasticsearchConfig {
    @Value("${elasticsearch.port}")
    private int port;

    @Value("${elasticsearch.ip}")
    private String ip;

    @Value("${elasticsearch.username}")
    private String username;

    @Value("${elasticsearch.password}")
    private String password;

    /**
     * 创建带HTTP Basic Auth认证rest客户端
     */
    @Bean
    public RestHighLevelClient restHighLevelClient() {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
        return new RestHighLevelClient(RestClient.builder(
                new HttpHost[]{
                    new HttpHost(ip, port, "http")
                }).setHttpClientConfigCallback((HttpAsyncClientBuilder httpAsyncClientBuilder) -> httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider)));
    }

    //不带用户名密码验证
    //@Bean
    public RestHighLevelClient restClient() {
        return new RestHighLevelClient(RestClient.builder(new HttpHost[]{
                new HttpHost(ip, port, "http")
        }));
    }
}

yml配置文件内容

server:
  # 服务端口
  port: 9990

elasticsearch:
  port: 9200
  ip: 127.0.0.1
  username: elastic
  password: 123456


# 查看es信息时需要的序列化
spring:
  jackson:
    serialization:
      FAIL_ON_EMPTY_BEANS: false

注入依赖

在controller下注入依赖

@Autowired
private RestHighLevelClient restHighLevelClient;

对索引的CURD

1、创建索引

/**
 * 创建索引
 *
 * @return
 * @throws IOException
 */
@GetMapping("/createIndex")
public Object createIndex() throws IOException {
	//1.创建索引请求
	CreateIndexRequest request = new CreateIndexRequest("testindex");
	//2.客户端执行请求IndicesClient,执行create方法创建索引,请求后获得响应
	CreateIndexResponse response =
			restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
	return response;
}

SpringBoot 整合ElasticSearch实现模糊查询,批量CRUD,排序,分页,高亮
可以看到已经添加成功了,但是一定注意,索引名称,一定要小写!

2、查询索引

/**
 * 查询索引
 *
 * @return
 * @throws IOException
 */
@GetMapping("/searchIndex")
public Object searchIndex() throws IOException {
	//1.查询索引请求
	GetIndexRequest request = new GetIndexRequest("testindex");
	//2.执行exists方法判断是否存在
	boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
	return exists;
}

3、删除索引

/**
 * 删除索引
 *
 * @return
 * @throws IOException
 */
@GetMapping("delIndex")
public Object delIndex() throws IOException {
	//1.删除索引请求
	DeleteIndexRequest request = new DeleteIndexRequest("testindex");
	//执行delete方法删除指定索引
	AcknowledgedResponse delete = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
	return delete.isAcknowledged();
}

对文档的CRUD

1、新增文档

注意:如果添加时不指定文档ID,他就会随机生成一个ID,ID唯一。

/**
 * 新增文档
 *
 * @return
 * @throws IOException
 */
@GetMapping("/add")
public Object add() throws IOException {
	//1.创建对象
	User user = new User("张三", 21);
	//2.创建请求(索引的名字)
	IndexRequest request = new IndexRequest("indexdocument");
	//3.设置规则 PUT /ljx666/_doc/1
	//设置文档id=6,设置超时=1s等,不设置会使用默认的
	//同时支持链式编程如 request.id("6").timeout("1s");
	request.id("6");
	// 指定要写入的 Index
	request.type("_doc");
	/*request.index("test");*/
	/*request.timeout(TimeValue.timeValueSeconds(1));*/
	request.timeout("1s");

	//4.将数据放入请求,要将对象转化为json格式
	//XContentType.JSON,告诉它传的数据是JSON类型
	request.source(JSON.toJSONString(user), XContentType.JSON);

	//5.客户端发送请求,获取响应结果
	IndexResponse indexResponse = restHighLevelClient.index(request, RequestOptions.DEFAULT);
	System.out.println(indexResponse.toString());
	System.out.println(indexResponse.status());
	return indexResponse;
}

2、查询文档中的数据

/**
 * 获取文档中的数据
 *
 * @return
 * @throws IOException
 */
@GetMapping("/get")
public Object get() throws IOException {
	//1.创建请求,指定索引、文档id(索引的名字)
	GetRequest request = new GetRequest("indexdocument").id("6").type("_doc");
	GetResponse getResponse = restHighLevelClient.get(request, RequestOptions.DEFAULT);
	System.out.println(getResponse);//获取响应结果
	//getResponse.getSource() 返回的是Map集合
	System.out.println(getResponse.getSourceAsString());//获取响应结果source中内容,转化为字符串
	return getResponse;
}

3、更新文档中的数据

注意:需要将User对象中的属性全部指定值,不然会被设置为空,如User只设置了名称,那么只有名称会被修改成功,其他会被修改为null。

/**
 * 更新文档数据
 *
 * @return
 * @throws IOException
 */
@GetMapping("/update")
public Object update() throws IOException {
	//1.创建请求,指定索引、文档id(索引的名字)
	UpdateRequest request = new UpdateRequest("indexdocument","_doc","6");

	User user = new User("小明", 21);
	//将创建的对象放入文档中
	request.doc(JSON.toJSONString(user), XContentType.JSON);
	UpdateResponse updateResponse = restHighLevelClient.update(request, RequestOptions.DEFAULT);
	System.out.println(updateResponse.status());//更新成功返回OK
	return updateResponse;
}

3、删除文档中的数据

/**
 * 删除文档数据
 *
 * @return
 * @throws IOException
 */
@GetMapping("/delete")
public Object delete() throws IOException {
	//1.创建删除文档请求
	DeleteRequest request = new DeleteRequest("indexdocument").id("6").type("_doc");
	DeleteResponse deleteResponse = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
	System.out.println(deleteResponse.status());//更新成功返回OK
	return deleteResponse;
}

4、批量新增文档中的数据

/**
 * 批量新增文档数据
 *
 * @return
 * @throws IOException
 */
@GetMapping("/addBatch")
public Object addBatch() throws IOException {
	BulkRequest bulkRequest = new BulkRequest();
	//设置超时
	bulkRequest.timeout("10s");

	List<User> list = new ArrayList<>();
	list.add(new User("李四", 25));
	list.add(new User("王五", 18));
	list.add(new User("赵六", 30));
	list.add(new User("田七", 26));
	list.add(new User("刘八", 20));

	int id = 1;
	//批量处理请求
	for (User user : list) {
		//不设置id会生成随机id
		bulkRequest.add(new IndexRequest("indexdocument")
				.id("" + (id++))
				.type("_doc")
				.source(JSON.toJSONString(user), XContentType.JSON));
	}

	BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
	System.out.println(bulkResponse.hasFailures());//是否执行失败,false为执行成功
	return bulkResponse;
}

5、询所有、模糊查询、分页查询、排序、高亮显示

/**
 * 复杂的es查询
 * @return
 * @throws IOException
 */
@GetMapping("test")
public Object test() throws IOException {
	SearchRequest searchRequest = new SearchRequest("indexdocument");//里面可以放多个索引
	SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();//构造搜索条件
	//此处可以使用QueryBuilders工具类中的方法
	//1.查询所有
	sourceBuilder.query(QueryBuilders.matchAllQuery());
	//2.查询name中含有Java的
	sourceBuilder.query(QueryBuilders.multiMatchQuery("张三", "name"));
	//3.分页查询
	sourceBuilder.from(0).size(5);
	//4.按照score正序排列
	sourceBuilder.sort(SortBuilders.scoreSort().order(SortOrder.ASC));
	//5.按照id倒序排列(score会失效返回NaN)
	sourceBuilder.sort(SortBuilders.fieldSort("_id").order(SortOrder.DESC));
	//6.给指定字段加上指定高亮样式
	HighlightBuilder highlightBuilder = new HighlightBuilder();
	highlightBuilder.field("name").preTags("<span style='color:red;'>").postTags("</span>");
	sourceBuilder.highlighter(highlightBuilder);
	searchRequest.source(sourceBuilder);
	SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
	//获取总条数
	System.out.println(searchResponse.getHits().getTotalHits());
	//输出结果数据(如果不设置返回条数,大于10条默认只返回10条)
	SearchHit[] hits = searchResponse.getHits().getHits();
	for (SearchHit hit : hits) {
		System.out.println("分数:" + hit.getScore());
		Map<String, Object> source = hit.getSourceAsMap();
		System.out.println("index->" + hit.getIndex());
		System.out.println("id->" + hit.getId());
		for (Map.Entry<String, Object> s : source.entrySet()) {
			System.out.println(s.getKey() + "--" + s.getValue());
		}
	}
	return searchResponse;
}

总结

1.大致流程

创建对应的请求 --> 设置请求(添加规则,添加数据等) --> 执行对应的方法(传入请求,默认请求选项)–> 接收响应结果(执行方法返回值)–> 输出响应结果中需要的数据(source,status等)

2.注意事项

如果不指定id,会自动生成一个随机id

正常情况下,不应该这样使用new IndexRequest(“indexName”),如果索引发生改变了,那么代码都需要修改,可以定义一个枚举类或者一个专门存放常量的类,将变量用final static等进行修饰,并指定索引值。其他地方引用该常量即可,需要修改也只需修改该类即可。

elasticsearch相关的东西,版本都必须一致,不然会报错

elasticsearch很消耗内存,建议在内存较大的服务器上运行elasticsearch,否则会因为内存不足导致elasticsearch自动killed

文章参考:https://blog.csdn.net/zhiyikeji/article/details/128902860文章来源地址https://www.toymoban.com/news/detail-478179.html

到了这里,关于SpringBoot 整合ElasticSearch实现模糊查询,批量CRUD,排序,分页,高亮的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包赞助服务器费用

相关文章

  • Java实战:SpringBoot+ElasticSearch 实现模糊查询

    本文将详细介绍如何使用SpringBoot整合ElasticSearch,实现模糊查询、批量CRUD、排序、分页和高亮功能。我们将深入探讨ElasticSearch的相关概念和技术细节,以及如何使用SpringData Elasticsearch库简化开发过程。 ElasticSearch是一个基于Lucene构建的开源搜索引擎,它提供了一个分布式、多

    2024年04月25日
    浏览(8)
  • SpringBoot整合ElasticSearch实现分页查询

    SpringBoot整合ElasticSearch实现分页查询

    本文使用SpringBoot整合ElasticSearch实现分页查询 还是继续使用spring-boot-starter-data-elasticsearch来实现分页查询操作 数据准备 使用ElasticsearchRestTemplate来实现 程序结果 使用ElasticsearchOperations来实现 程序结果 本文记录了SpringBoot整合ElasticSearch来实现分页查询的两种方式

    2024年01月25日
    浏览(9)
  • springboot整合neo4j模糊查询

    1.场景 查询与content相似的实体 解决方案: 1.直接从neo4j中查询所有实体并使用杰卡德相似度算法计算相似度,返回top n,该方案由于要匹配图中所有实体,性能较差。 2.模糊查询neo4j中的实体,并对查询结果与content做相似度计算,相似度算法为hutool中的TextSimilarity.similar()接口

    2024年02月13日
    浏览(8)
  • springboot整合elasticsearch实现类似于mysql的like查询

    目录 一、ES分页查询常用方式 二、引入es的依赖 三、es配置文件 四、es工具类 五、分页查询示例 1.from + size from表示从第几行开始,size表示查询多少条文档。from默认为0,size默认为10,最灵活的分页方式。 2.scroll 不适合用来做实时搜索,而更适用于后台批处理任务,如日志导

    2023年04月09日
    浏览(5)
  • SpringBoot整合Elasticsearch实现分页条件查询及注意事项

    项目环境: springboot 2.3.7.RELEASE es 6.8.3 这里需要注意es中日期格式,ES默认是不支持yyyy-MM-dd HH:mm:ss格式的,需要通过 @Field(type = FieldType.Date, format = DateFormat.custom,pattern = \\\"yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_second\\\") 来指定日期格式。 直接看业务层实现分页条件查询: 范围查询: es en

    2023年04月16日
    浏览(9)
  • Springboot整合mybatis实现增删改查(crud)

    Springboot整合mybatis实现增删改查(crud)

    今天我们来学习一个Springboot案例!! 那么什么是SpringBoot技术呢? Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。 该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。 Spring Boot致力于在蓬

    2024年01月22日
    浏览(6)
  • Springboot整合Elasticsearch 7.X 复杂查询

    Springboot整合Elasticsearch 7.X 复杂查询

    这里使用Springboot 2.7.12版本,Elasticsearch为7.15.0。 导入依赖 yaml文件配置: 构建实体类,这里为商品的SKU属性表 构建service层进行复杂查询:指定条件查询,聚合查询,分页查询,排序查询,高亮等等 接口测试: 查询如下:      

    2024年02月03日
    浏览(6)
  • Springboot整合Elasticsearch新版分页查询

    其它插入、删除、简单查询都可以通过Repository调用方法查询。 Elasticsearch现在的新版本已经弃用了ElasticsearchTemplate类,Repository里原来的search方法也已经弃用了。下面是使用ElasticsearchRestTemplate类实现的分页查询 代码

    2024年02月11日
    浏览(5)
  • springboot整合elasticsearch8组合条件查询

    整合过程见上一篇文章 springboot整合elasticsearch8 1.es8多条件组合查询 2.使用scroll进行大数据量查询

    2024年02月16日
    浏览(11)
  • ElasticSearch系列 - SpringBoot整合ES:组合多个查询条件 bool 查询

    01. ElasticSearch 布尔查询是什么? 在实际应用中,我们很有可能会查询多个值或字段。 一个 bool 查询由三部分组成: must:所有的语句都必须(must) 匹配,与 AND 等价。 must_not:所有的语句都不能(must not)匹配,与 NOT 等价。 should:至少有一个语句要匹配,与 OR 等价。 02.

    2023年04月08日
    浏览(9)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包