elasticsearch java客户端基本操作学习: 索引,文档,检索
前提
版本:
elasticsearch版本: 8.3.2
elasticsearch-java: 8.3.2
问题: springboot项目可能冲突,抛出异常文章来源:https://www.toymoban.com/news/detail-541653.html
ClassNotFoundException: jakarta.json.spi.JsonProvider
解决:添加依赖,具体解决方法: https://www.elastic.co/guide/en/elasticsearch/client/java-api-client/current/installation.html文章来源地址https://www.toymoban.com/news/detail-541653.html
<dependency>
<groupId>jakarta.json</groupId>
<artifactId>jakarta.json-api</artifactId>
<version>2.0.1</version>
</dependency>
添加maven依赖
<dependency>
<groupId>co.elastic.clients</groupId>
<artifactId>elasticsearch-java</artifactId>
<version>8.3.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.3</version>
</dependency>
<dependency>
<groupId>jakarta.json</groupId>
<artifactId>jakarta.json-api</artifactId>
<version>2.0.1</version>
</dependency>
连接elasticsearch客户端
private static final String TEST_INDEX = "test_demo";
private static ElasticsearchTransport transport;
private static ElasticsearchClient client;
public static void main(String[] args) throws IOException {
//连接
esInit();
//操作
operationDoc();
//关闭连接
transport.close();
}
// 连接
private static void esInit() {
// Create the low-level client
RestClient restClient = RestClient.builder(
new HttpHost("localhost", 9200)).build();
// Create the transport with a Jackson mapper
transport = new RestClientTransport(
restClient, new JacksonJsonpMapper());
// And create the API client
client = new ElasticsearchClient(transport);
}
索引操作
查询索引是否存在
boolean exit = client.indices().exists(builder -> builder.index(TEST_INDEX)).value();
创建索引
if (!exit) {
// 创建索引
client.indices().create(builder -> builder.index(TEST_INDEX));
}
删除索引
client.indices().delete(builder -> builder.index(TEST_INDEX));
文档操作
删除文档
// 删除文档,批量操作
client.bulk(builder -> {
for (int i = 4000; i < 4004; i++) {
int finalI = i;
BulkOperation operation = new BulkOperation.Builder().delete(d -> {
// TEST_INDEX: 索引名称
// id: 文档id
d.index(TEST_INDEX).id(String.valueOf(finalI));
return d;
}).build();
builder.operations(operation);
}
return builder;
});
新增文档
@Data
public class User implements Serializable {
private Integer id;
private String name;
private Integer age;
public User(Integer id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}
}
// 数据准备
User zhang_san = new User(4000, "zhang san", 20);
User zhang_san_feng = new User(4001, "zhang san feng", 30);
User zhang_wu_ji = new User(4002, "zhang wu ji", 40);
User zhang_yi_feng = new User(4003, "zhang yi feng", 50);
List<User> userList = Arrays.asList(zhang_san, zhang_san_feng, zhang_wu_ji, zhang_yi_feng);
// 批量新增文档
client.bulk(builder -> {
for (User user : userList) {
BulkOperation operation = new BulkOperation.Builder().create(c -> {
// TEST_INDEX: 索引名称
// id: 文档id
// document: 文档
c.index(TEST_INDEX).id(user.getId().toString()).document(user);
return c;
}).build();
builder.operations(operation);
}
return builder;
});
获取文档
Map userMap = client.get(builder -> {
builder.index(TEST_INDEX).id("4000");
return builder;
}, Map.class).source();
System.out.println(userMap);
修改文档
// 修改文档
client.update(builder -> {
User zhang_san_new = new User(4000, "zhang san new", 60);
builder.index(TEST_INDEX).id("4000").doc(zhang_san_new);
return builder;
}, Map.class);
删除文档
// 删除文档
client.delete(builder -> {
builder.index(TEST_INDEX).id("4000");
return builder;
});
条件查询
// 条件查询,查询结果用 Object 接收
List<Hit<Object>> hits = client.search(builder -> {
builder
// 要查询的索引
.index(TEST_INDEX)
// 排序
.sort(sort())
// 查询
.query(query());
return builder;
}, Object.class).hits().hits();
// 结果遍历
for (Hit<Object> hit : hits) {
System.out.println(hit.source());
}
// 排序
private static List<SortOptions> sort() {
List<SortOptions> sortOptionsList = new ArrayList<>();
// 创建 SortOptions 对象, 排序字段: age, 排序方式: SortOrder.Asc
SortOptions sortOptions = new SortOptions.Builder().field(builder -> builder.field("age").order(SortOrder.Asc)).build();
// 多个排序字段 ...
sortOptionsList.add(sortOptions);
return sortOptionsList;
}
//条件查询
private static Query query() {
// match 会分词查询
Query matchQuery = new Query.Builder().match(builder -> {
// 查询名字包含 zhang 的数据
// 例如 zhang san, zhang san feng, zhang wu ji,zhang yi feng 可以被检索到
builder.field("name").query("zhang");
return builder;
}).build();
// matchPhrase 短语查询
Query matchPhraseQuery = new Query.Builder().matchPhrase(builder -> {
// 查询名字包含 "zhang san" 这个短语(两个词一定是连续,像zhang yi san是查不到的)
// 例如 zhang san, zhang san feng可以被检索到,
// 而zhang wu ji, zhang yi san 不可以被检索到
builder.field("name").query("zhang san");
return builder;
}).build();
// term 精确查询
Query termQuery = new Query.Builder().term(builder -> {
// zhang san 会被elasticsearch分词为zhang和san,
// 当查询zhang san会被当一个整体查找,词库没有这个整体,会找不到数据
// builder.field("name").value("zhang san");
// 可以通过添加 .keyword 精确查找
builder.field("name.keyword").value("zhang san");
return builder;
}).build();
// 模糊查询
Query wildcardQuery = new Query.Builder().wildcard(builder -> {
builder.field("name").value("*zh*");
return builder;
}).build();
// 范围查询
Query rangeQuery = new Query.Builder().range(builder -> {
builder.field("age").gt(JsonData.of(30));
return builder;
}).build();
// 多个条件查询 BoolQuery
// must: 条件必修满足,类似SQL AND
// should: 条件或者满足,类似SQL OR
// filter: 过滤结果, 类似stream流filter
// mustNot: 条件必须不满足,类似SQL NOT
BoolQuery boolQuery = new BoolQuery.Builder()
// .must(termQuery)
// .should()
// .filter()
// .mustNot()
.build();
return new Query.Builder().bool(boolQuery).build();
}
到了这里,关于elasticsearch-java客户端操作的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!