elasticsearch api 调用
Posted lz527657138
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了elasticsearch api 调用相关的知识,希望对你有一定的参考价值。
elasticsearch
文章目录
- 说明
- 下载安装 elasticsearch
- 依赖
- 初始化 es 客户端
- 创建索引
- 查看索引
- 删除索引
- 创建文档
- 通过id查看文档
- 修改文档
- 通过id删除文档
- 条件查询
- 分页查询
- 查询过滤字段
- 条件查询
- 聚合查询
说明
请先看理论知识, 再看代码, 事半功倍! 有些代码的测试数据可能不全, 旨在理解API的调用, 所以…
下载安装 elasticsearch
这里下载安装的版本是 elasticsearch-7.8.0
依赖
<dependencies>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.8.0</version>
</dependency>
<!-- elasticsearch 的客户端 -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.8.0</version>
</dependency>
<!-- elasticsearch 依赖 2.x 的 log4j -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.8.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.8.2</version>
</dependency>
<!-- junit 单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- 一个小而全的Java工具类库(推荐使用) -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.3</version>
</dependency>
</dependencies>
初始化 es 客户端
public void initESClient() throws IOException
//创建 es 客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http"))
);
//业务代码区 -- begin
//TODO
//业务代码区 -- end
//关闭 es 客户端
esClient.close();
创建索引
public void createIndex() throws IOException
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http"))
);
//使用 CreateIndexRequest 创建 user 索引
CreateIndexRequest request = new CreateIndexRequest("user");
CreateIndexResponse response = esClient.indices().create(request, RequestOptions.DEFAULT);
boolean acknowledged = response.isAcknowledged();
System.out.println("索引创建" + (acknowledged?"成功!":"失败!"));
esClient.close();
查看索引
public void getIndex() throws IOException
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http"))
);
//查看 user 索引
GetIndexRequest request = new GetIndexRequest("user");
GetIndexResponse response = esClient.indices().get(request, RequestOptions.DEFAULT);
System.out.println("aliases: " + response.getAliases());
System.out.println("mappings: " + response.getMappings());
System.out.println("settings: " + response.getSettings());
esClient.close();
删除索引
public void delete() throws IOException
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http"))
);
DeleteIndexRequest request = new DeleteIndexRequest("car");
AcknowledgedResponse response = esClient.indices().delete(request, RequestOptions.DEFAULT);
boolean acknowledged = response.isAcknowledged();
System.Elasticsearch 5.4.3实战--Java API调用:搜索建议