本示例使用springboot版本是2.3.1
org.elasticsearch.client
elasticsearch-rest-high-level-client
7.4.2
注意: 这里的版本号要和elasticsearch的版本要一一对应
检查elasticsearch的依赖版本是否一致
如果不一样,检查springboot 父项目依赖版本
@Configuration
public class ElasticsearchConfig {
@Bean
public RestHighLevelClient esRestClient(){
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("192.168.126.20", 9200, "http")));
return client;
}
}
测试,是否可以和es通信
@SpringBootTest
class GulimallSearchApplicationTests {
@Autowired
private RestHighLevelClient client;
@Test
void contextLoads() {
System.out.println(client);
}
}
@Configuration
public class ElasticsearchConfig {
public static final RequestOptions COMMON_OPTIONS;
static {
RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
/*builder.addHeader("Authorization", "Bearer " + TOKEN);
builder.setHttpAsyncResponseConsumerFactory(
new HttpAsyncResponseConsumerFactory
.HeapBufferedResponseConsumerFactory(30 * 1024 * 1024 * 1024));*/
COMMON_OPTIONS = builder.build();
}
@Bean
public RestHighLevelClient esRestClient(){
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("192.168.126.20", 9200, "http")));
return client;
}
}
执行测试方法
/**
* 测试 存储数据
*/
@Test
void indexData() throws IOException {
IndexRequest indexRequest = new IndexRequest("users");
indexRequest.id("1");
//indexRequest.source("userName","张三","age",23,"gender","男");
User user = new User();
user.setUserName("张三");
user.setAge(23);
user.setGender("男");
String jsonString = JSON.toJSONString(user);
indexRequest.source(jsonString, XContentType.JSON);
// 执行保存操作
IndexResponse response = client.index(indexRequest, ElasticsearchConfig.COMMON_OPTIONS);
//提取 相应数据
System.out.println(response);
}
@Data
class User{
private String userName;
private Integer age;
private String gender;
}
执行结果:
IndexResponse[index=users,type=_doc,id=1,version=1,result=created,seqNo=0,primaryTerm=1,shards={"total":2,"successful":1,"failed":0}]
使用kibana查询
GET users/_search
检索结果
{
"took" : 117,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : 1.0,
"hits" : [
{
"_index" : "users",
"_type" : "_doc",
"_id" : "1",
"_score" : 1.0,
"_source" : {
"age" : 23,
"gender" : "男",
"userName" : "张三"
}
}
]
}
}
需求: 查询 地址包含"mill",年龄段,以及总的平均薪资
import com.alibaba.fastjson.JSON;
import com.atguigu.gulimall.search.config.ElasticsearchConfig;
import lombok.Data;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.Avg;
import org.elasticsearch.search.aggregations.metrics.AvgAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import javax.swing.text.StyledEditorKit;
import java.io.IOException;
import java.util.List;
import java.util.Map;
@SpringBootTest
class GulimallSearchApplicationTests {
@Autowired
@Qualifier("esRestClient")
private RestHighLevelClient client;
@Data
static class Account {
private int account_number;
private int balance;
private String firstname;
private String lastname;
private int age;
private String gender;
private String address;
private String employer;
private String email;
private String city;
private String state;
}
@Test
void searchData() throws IOException {
// 1. 创建检索请求
SearchRequest searchRequest = new SearchRequest();
//指定检索索引
searchRequest.indices("bank");
//指定检索条件DSL
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//构造检索条件
searchSourceBuilder.query(QueryBuilders.matchQuery("address","mill"));
//按照年龄的值分布进行聚合
TermsAggregationBuilder ageAgg = AggregationBuilders.terms("ageAgg").field("age").size(10);
searchSourceBuilder.aggregation(ageAgg);
//计算平均薪资
AvgAggregationBuilder balanceAgg = AggregationBuilders.avg("balanceAgg").field("balance");
searchSourceBuilder.aggregation(balanceAgg);
searchRequest.source(searchSourceBuilder);
//2. 执行检索
SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
//3. 分析结果
//Map map = JSON.parseObject(response.toString(), Map.class);
//3.1 获取查到 数据
SearchHits hits = response.getHits();
SearchHit[] searchHits = hits.getHits();//真正的命中记录
for (SearchHit hit : searchHits) {
String sourceAsString = hit.getSourceAsString();
Account account = JSON.parseObject(sourceAsString, Account.class);
System.out.println("account: " + account.toString());
}
//3.2 获取检索 聚合信息
Aggregations aggregations = response.getAggregations();
Terms ageAgg1 = aggregations.get("ageAgg");
for (Terms.Bucket bucket : ageAgg1.getBuckets()) {
String keyAsString = bucket.getKeyAsString();
long docCount = bucket.getDocCount();
System.out.println("年龄: " + keyAsString + "人数: " + docCount);
}
Avg avg = aggregations.get("balanceAgg");
System.out.println("平均薪资: " + avg.getValue());
}
@Test
void contextLoads() {
System.out.println(client);
}
}
执行结果如下:
account: GulimallSearchApplicationTests.Account(account_number=970, balance=19648, firstname=Forbes, lastname=Wallace, age=28, gender=M, address=990 Mill Road, employer=Pheast, [email protected], city=Lopezo, state=AK)
account: GulimallSearchApplicationTests.Account(account_number=136, balance=45801, firstname=Winnie, lastname=Holland, age=38, gender=M, address=198 Mill Lane, employer=Neteria, [email protected], city=Urie, state=IL)
account: GulimallSearchApplicationTests.Account(account_number=345, balance=9812, firstname=Parker, lastname=Hines, age=38, gender=M, address=715 Mill Avenue, employer=Baluba, [email protected], city=Blackgum, state=KY)
account: GulimallSearchApplicationTests.Account(account_number=472, balance=25571, firstname=Lee, lastname=Long, age=32, gender=F, address=288 Mill Street, employer=Comverges, [email protected], city=Movico, state=MT)
年龄: 38人数: 2
年龄: 28人数: 1
年龄: 32人数: 1
平均薪资: 25208.0
更多内容见官方文档