Java ‘Elasticsearch‘ 操作

依赖

复制代码
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-elasticsearch -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
    <version>2.3.12.RELEASE</version>
</dependency>

配置

复制代码
spring:
  elasticsearch:
    uris: http://192.168.0.226:9200

对象

复制代码
@Autowired
private ElasticsearchRestTemplate elasticsearchRestTemplate;

添加索引操作

复制代码
elasticsearchRestTemplate.indexOps(IndexCoordinates.of("indexname")).create();

IndexCoordinates可以给多个索引

删除索引

elasticsearchRestTemplate.indexOps(IndexCoordinates.of("indexname")).delete();

添加操作

复制代码
IndexQuery indexQuery = new IndexQueryBuilder()
        .withId(productId)
                .withObject(product4ES)
                        .build();
elasticsearchRestTemplate.index(indexQuery, IndexCoordinates.of("products"));

查询操作

这个类是封装查询数据的

NativeSearchQuery query = new NativeSearchQueryBuilder()

要查询的字段

.withQuery(multiMatchQuery(keyword, "productName", "productSkuName"))

分页由于里面比尔帮你做好了就不要套用公式了

.withPageable(PageRequest.of(pageNum - 1, limit))

这里是高亮显示,用的是可变参数

.withHighlightFields(new HighlightBuilder.Field("productName").preTags("<label style='color: red'>").postTags("</label>"), new HighlightBuilder.Field("productSkuName").preTags("<label style='color: red'>").postTags("</label>"))

这里是构建

.build();

复制代码
elasticsearchRestTemplate.search调用这个方法
复制代码
search(封装的查询调教, 里面装的类型自动的, IndexCoordinates.of("要差的索引"))
复制代码
SearchHits得到这个
复制代码
search.getTotalHits();获取查询到的count

product4ES是我自己创建的然后装得到index

获取搜索的结果

复制代码
List<SearchHit<Product4ES>> searchHits = search.getSearchHits();
创建一个等等用
List<Product4ES> list = new ArrayList<>();
for (SearchHit<Product4ES> hit : searchHits) {
获取返回的对象用什么对象装的什么对象拿自动的
    Product4ES product4ES = hit.getContent();
获取高亮map对象多个高亮map就有多个值
    Map<String, List<String>> highlightFields = hit.getHighlightFields();
获取叫下面这个名字的字段的高亮文本这里可能一段文字多个高亮
    List<String> productName = highlightFields.get("productName");
    if (!productName.isEmpty()) {
拿到第一个高亮,并设置
        product4ES.setProductName(productName.get(0));
    }
设置到对象
    list.add(product4ES);
}

计算总页数

复制代码
int pageCount = ((int) (count % limit == 0 ? count / limit : count / limit + 1));
相关推荐
xiaoye37081 小时前
Java 自动装箱 / 拆箱 原理详解
java·开发语言
YDS8292 小时前
黑马点评 —— 分布式锁详解加源码剖析
java·spring boot·redis·分布式
ZTLJQ2 小时前
数据的基石:Python中关系型数据库完全解析
开发语言·数据库·python
夏霞3 小时前
c# signlar 客户端传递参数给服务端配置方法
开发语言·c#
迷藏4943 小时前
**发散创新:基于 Rust的开源权限管理系统设计与实战**在现代软件架构中,**权限控制**早已不
java·开发语言·rust·开源
升鲜宝供应链及收银系统源代码服务3 小时前
《IntelliJ + Claude Code + Gemini + ChatGPT 实战配置手册升鲜宝》
java·前端·数据库·chatgpt·供应链系统·生鲜配送
daidaidaiyu3 小时前
Nacos实例一则及其源码环境搭建
java·spring
2301_818419013 小时前
C++中的解释器模式变体
开发语言·c++·算法
小江的记录本3 小时前
【Redis】Redis全方位知识体系(附《Redis常用命令速查表(完整版)》)
java·数据库·redis·后端·python·spring·缓存
摇滚侠4 小时前
Java 项目《谷粒商城-1》架构师级Java 项目实战,对标阿里 P6-P7,全网最强,实操版本
java·开发语言