0%

ElasticSearch基于JavaApi

ElasticSearch

创建maven项目,引入elasticsearch依赖,使用版本7.8.0

1
2
3
4
5
6
7
8
9
10
11
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.8.0</version>
</dependency>
<!-- es客户端 -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.8.0</version>
</dependency>

创建es客户端

1
2
3
4
5
6
7
8
9
10
public static void main(String[] args) throws IOException {
// 创建es客户端
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("127.0.0.1", 9200, "http")));

// 关闭客户端
client.close();

}

创建索引

1
2
3
4
5
6
// 创建索引
CreateIndexResponse order = client.indices().create(new CreateIndexRequest("order"), RequestOptions.DEFAULT);
// 创建结果
boolean acknowledged = order.isAcknowledged();

System.out.println("创建结果: " + (acknowledged ? "成功": "失败"));

查询索引信息

1
2
3
4
5
6
7
// 查询索引
GetIndexResponse order = client.indices().get(new GetIndexRequest("order"), RequestOptions.DEFAULT);
// 打印相关信息; 索引的别名、结构、设置信息
System.out.println(order.getAliases());
System.out.println(order.getMappings());
System.out.println(order.getSettings());

删除索引

1
2
3
4
// 删除索引
AcknowledgedResponse order = client.indices().delete(new DeleteIndexRequest("order"),RequestOptions.DEFAULT);
boolean acknowledged = order.isAcknowledged();
System.out.println("删除索引结果: " + (acknowledged ? "successful": "failure"));

创建文档

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 创建文档
IndexRequest indexRequest = new IndexRequest("order");
// 指定id
indexRequest.id("1002");
// 创建数据,并转换成json格式
Order order = new Order();
order.setName("手机");
order.setDesc("小米&xiaomi12");
order.setCount(1);
order.setPrice(3999.99);
String json = new ObjectMapper().writeValueAsString(order);
// 文档数据格式指定为json
indexRequest.source(json, XContentType.JSON);
// 创建文档
IndexResponse index = client.index(indexRequest, RequestOptions.DEFAULT);
// 查看返回结果
System.out.println(index.getResult());

更新文档

1
2
3
4
5
6
7
8
// 更新文档
UpdateRequest order = new UpdateRequest();
// 执行需要修改的索引以及文档id
order.index("order").id("1002");
// 局部修改
order.doc(XContentType.JSON, "price", 2999.00);
UpdateResponse update = client.update(order, RequestOptions.DEFAULT);
System.out.println(update.getResult());

查询

1
2
3
4
5
6
// 查询数据
GetRequest getRequest = new GetRequest();
getRequest.index("order").id("1002");
GetResponse documentFields = client.get(getRequest, RequestOptions.DEFAULT);
String sourceAsString = documentFields.getSourceAsString();
System.out.println(sourceAsString);

删除

1
2
3
4
5
// 删除文档
DeleteRequest deleteRequest = new DeleteRequest();
deleteRequest.index("order").id("1003");
DeleteResponse delete = client.delete(deleteRequest, RequestOptions.DEFAULT);
System.out.println(delete.getResult());

全量查询

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// 批量插入数据
// BulkRequest bulkRequest = new BulkRequest();
// bulkRequest.add(new IndexRequest().index("order").id("1004").source(XContentType.JSON, "name", "电脑", "desc", "笔记本", "count", 1, "price", 12999.00));
// bulkRequest.add(new IndexRequest().index("order").id("1005").source(XContentType.JSON, "name", "电风扇", "desc", "美的电风扇", "count", 1, "price", 1999.00));
// bulkRequest.add(new IndexRequest().index("order").id("1006").source(XContentType.JSON, "name", "手表", "desc", "Apple Watch S8", "count", 1, "price", 2999.00));
// bulkRequest.add(new IndexRequest().index("order").id("1007").source(XContentType.JSON, "name", "耳机", "desc", "AirPods", "count", 1, "price", 1999.00));
// BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
// TimeValue took = bulk.getTook();
// System.out.println(took);

// 条件查询
SearchRequest searchRequest = new SearchRequest();
// 指定索引
searchRequest.indices("order");
// 构建查询, QueryBuilders.matchAllQuery()查询所有数据
SearchSourceBuilder query = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
searchRequest.source(query);
SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
for (SearchHit hit : search.getHits()) {
System.out.println(hit.getSourceAsString());
}

条件查询&分页&排序&字段过滤

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// 条件查询
SearchRequest searchRequest = new SearchRequest();
// 指定索引
searchRequest.indices("order");
// 构建查询, QueryBuilders.matchQuery()查询匹配的数据
SearchSourceBuilder query = new SearchSourceBuilder().query(QueryBuilders.matchQuery("name", "手机"));
// 分页
query.from(0).size(3);
// 排序 desc降序,asc升序
query.sort("price", SortOrder.DESC);
// 过滤显示的字段
// 包含的字段
String[] includes = {"name", "price"};
// 排除的字段
String[] excludes = {"count"};
query.fetchSource(includes, excludes);
searchRequest.source(query);
SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
for (SearchHit hit : search.getHits()) {
System.out.println(hit.getSourceAsString());
}

组合查询(多条件组合查询、范围查询)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// 条件查询
SearchRequest searchRequest = new SearchRequest();
// 指定索引
searchRequest.indices("order");
// 构建查询,
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
// should = or must = and
// 相当于: count = 1 and (price = 1999.0 || price = 2999.0) and price > 1999 and price < 2999
boolQueryBuilder.must(QueryBuilders.matchQuery("count", "1"));
BoolQueryBuilder boolQueryBuilderOr = QueryBuilders.boolQuery();
boolQueryBuilderOr.should(QueryBuilders.matchQuery("price", 1999.0));
boolQueryBuilderOr.should(QueryBuilders.matchQuery("price", 2999.0));
boolQueryBuilder.must(boolQueryBuilderOr);
// searchSourceBuilder.query(boolQueryBuilder);
// 范围查询, gt 大于 lt 小于 gte 大于等于 lte 小于等于
BoolQueryBuilder boolQueryBuilderAnd = QueryBuilders.boolQuery();
RangeQueryBuilder priceQuery = QueryBuilders.rangeQuery("price");
priceQuery.gt(2000).lt(4000);
boolQueryBuilderAnd.must(priceQuery);
boolQueryBuilder.must(boolQueryBuilderAnd);
searchSourceBuilder.query(boolQueryBuilder);

searchRequest.source(searchSourceBuilder);
SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
for (SearchHit hit : search.getHits()) {
System.out.println(hit.getSourceAsString());
}

模糊查询&高亮查询

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 模糊查询
SearchRequest searchRequest = new SearchRequest();
// 指定索引
searchRequest.indices("order");
// 构建模糊查询,
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// Fuzziness.TWO 指定条件匹配的偏差量
FuzzyQueryBuilder fuzziness = QueryBuilders.fuzzyQuery("name", "手表").fuzziness(Fuzziness.ONE);
// 高亮显示
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.preTags("<font color='red'>").postTags("</font>").field("name");
searchSourceBuilder.highlighter(highlightBuilder);
searchSourceBuilder.query(fuzziness);
searchRequest.source(searchSourceBuilder);
SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
for (SearchHit hit : search.getHits()) {
System.out.println(hit.getSourceAsString());
}

分组查询

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 聚合查询
SearchRequest searchRequest = new SearchRequest();
// 指定索引
searchRequest.indices("order");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// 聚合函数
// 最大值
// AggregationBuilder aggregationBuilder = AggregationBuilders.max("max_age").field("price");
// 分组
AggregationBuilder aggregationBuilder = AggregationBuilders.terms("max_group").field("price");
searchSourceBuilder.aggregation(aggregationBuilder);
searchRequest.source(searchSourceBuilder);
SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
for (SearchHit hit : search.getHits()) {
System.out.println(hit.getSourceAsString());
}

PS:github地址: https://github.com/Alwaysbryant/es-study-javaapi.git

-------------本文结束感谢您的阅读-------------