当前位置: 首页 > news >正文

Elasticsearch 8.x 在 java 中的使用情况

在 Java Spring Boot 微服务中集成 Elasticsearch 8.x,推荐使用官方的 Elasticsearch Java API Client(不同于 7.x 的 High Level REST Client)。

以下是 Elasticsearch 8.x 集成常用 API 及使用示例

✅ 一、依赖配置(Maven)

<dependency><groupId>co.elastic.clients</groupId><artifactId>elasticsearch-java</artifactId><version>8.11.1</version> <!-- 使用最新 8.x 版本 -->
</dependency>

✅ 二、客户端配置(Spring Bean)

@Configuration
public class ElasticsearchConfig {@Beanpublic ElasticsearchClient elasticsearchClient() {RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());return new ElasticsearchClient(transport);}
}

🔍 三、常用 API 和查询示例

1. Indexing(写入文档)

elasticsearchClient.index(i -> i.index("products").id("1").document(new Product("iPhone 15", 799.0))
);

2. Match 查询(全文搜索)

SearchResponse<Product> response = elasticsearchClient.search(s -> s.index("products").query(q -> q.match(m -> m.field("name").query("iPhone"))),Product.class
);

3. Term 查询(精确匹配)

elasticsearchClient.search(s -> s.index("products").query(q -> q.term(t -> t.field("status.keyword").value("active"))),Product.class
);

4. Bool 查询(多条件组合)

elasticsearchClient.search(s -> s.index("products").query(q -> q.bool(b -> b.must(m -> m.match(mm -> mm.field("name").query("iPhone"))).filter(f -> f.range(r -> r.field("price").gte(JsonData.of(500)).lte(JsonData.of(1000)))))),Product.class
);

5. 分页 + 排序

elasticsearchClient.search(s -> s.index("products").from(0).size(10).sort(sort -> sort.field(f -> f.field("price").order(SortOrder.Desc))),Product.class
);

6. 删除文档

elasticsearchClient.delete(d -> d.index("products").id("1")
);

✅ 四、实体类示例(Product)

public class Product {private String name;private double price;// Constructors, getters, setters...
}

📌 小结:常用 API 关键点

功能API 调用
写入文档client.index()
全文搜索query().match()
精确匹配query().term()
复合查询query().bool()
分页 & 排序from(), size(), sort()
删除client.delete()
http://www.xdnf.cn/news/326683.html

相关文章:

  • MIT关节电机相序校准
  • upload-labs靶场通关详解:第二关
  • 绕线机的制作与研究
  • very_easy_sql(SSRF+SQL注入)
  • 配置指定地址的conda虚拟Python环境
  • gitcode 上传文件报错文件太大has exceeded the limited size (10 MiB) in commit
  • dragonfly Prometheus 没有监控指标 dragonfly_scheduler_host_traffic
  • 益鑫通连接器车规级,非车规可替代JST,MOLEX
  • Keil安装pack包时报错解决:Cannot copy license file to “.Download“ folder.
  • string--OJ3
  • 基于Django框架开发的B2C天天生鲜电商平台
  • 306.检查是否所有A都在B之前
  • 通用分布式锁组件
  • 【优化策略】离散化
  • 力扣92.反转指定范围内的链表、25.k个一组反转链表
  • SpringBoot优雅参数检查
  • java基础-数组
  • AI训练服务器概述
  • 【信息系统项目管理师】法律法规与标准规范——历年考题(2024年-2020年)
  • 【fastadmin开发实战】财务数据快速导入系统(复制导入)
  • 配置Hadoop集群-测试使用
  • C# NX二次开发:曲线和点位相关UFUN函数详解
  • 游戏中心首页
  • LeetCode:对称二叉树
  • 贵州省棒球运动发展中长期规划(2024-2035)·棒球1号位
  • MySQL 联合查询的使用教程
  • Consumer Group的作用是什么?Rebalance的触发条件有哪些? (实现消费者负载均衡;消费者加入/离开、订阅Topic变化等)
  • JAVA中常见队列详解-非线程安全
  • by 组态在化工生产线自动化控制中的应用方案
  • 工具分享:通过滑块拉取CAN报文信号数值自动发送报文