1.导入依赖
这里的版本要和所按照的ELK版本匹配。
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.6.2</version>
</dependency>
在spring-boot-dependencies中所依赖的ELK版本位6.8.7
<elasticsearch.version>6.8.7</elasticsearch.version>
需要在项目中将它改为7.6.2
<properties>
...
<elasticsearch.version>7.6.2</elasticsearch.version>
</properties>
2.编写配置
package com.youzi.gulimall.search.config;
import org.apache.http.HttpHost;
import org.elasticsearch.client.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @Author youzi
* @ClassName GulimallElasticSearchConfig
* @Date 2022/5/6 9:42
* @Description //TODO
*/
/**
* 1.导入依赖
* 2.编写配置,给容器中注入一个RestHighLevelClient
* 3.参照API https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high.html
*/
@Configuration
public class GulimallElasticSearchConfig {
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() {
RestClientBuilder builder = null;
//final String hostname, final int port, final String scheme
builder = RestClient.builder(new HttpHost("106.13.234.61", 9200, "http"));
RestHighLevelClient client = new RestHighLevelClient(builder);
// RestHighLevelClient client = new RestHighLevelClient(
// RestClient.builder(
// new HttpHost("106.13.234.61", 9200, "http")));
return client;
}
}
3.编写测试类
package com.youzi.gulimall.search;
import com.alibaba.fastjson.JSON;
import com.youzi.gulimall.search.config.GulimallElasticSearchConfig;
import lombok.Data;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.IOException;
@SpringBootTest
public class GulimallSearchApplicationTests {
@Autowired
private RestHighLevelClient client;
/**
* 测试存储数据到es
* 更新也可以
*/
@Test
public void indexData() throws IOException {
IndexRequest indexRequest = new IndexRequest("users");
//数据的ID
indexRequest.id("1");
// indexRequest.source("userName","zhangsan","age",18,"gender","男");
Users users = new Users();
users.setUserName("张三");
users.setAge(18);
users.setGender("男");
String jsonString = JSON.toJSONString(users);
//要保存的内容
indexRequest.source(jsonString, XContentType.JSON);
//执行保存操作
IndexResponse index = client.index(indexRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);
//提取有用的相应数据
System.out.println(index);
}
@Data
class Users {
private String userName;
private String gender;
private Integer age;
}
@Test
public void contextLoads() {
System.out.println(client);
}
}
输出:
IndexResponse[index=users,type=_doc,id=1,version=2,result=updated,seqNo=1,primaryTerm=1,shards={"total":2,"successful":1,"failed":0}]
结果如图显示:
4.测试复杂检索
package com.youzi.gulimall.search;
import com.alibaba.fastjson.JSON;
import com.youzi.gulimall.search.config.GulimallElasticSearchConfig;
import lombok.Data;
import lombok.ToString;
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.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.boot.test.context.SpringBootTest;
import java.io.IOException;
@SpringBootTest
public class GulimallSearchApplicationTests {
@Autowired
private RestHighLevelClient client;
@Test
public void searchData() throws IOException {
//1.创建检索请求
SearchRequest searchRequest = new SearchRequest();
//指定索引
searchRequest.indices("bank");
//指定DSL,检索条件
//SearchSourceBuilder sourceBuilder
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//1.1构造检索条件
// sourceBuilder.query();
// sourceBuilder.from();
// sourceBuilder.size();
// sourceBuilder.aggregation();
sourceBuilder.query(QueryBuilders.matchQuery("address", "mill"));
//聚合函数
//1.2按照年龄的值分布,进行聚合
TermsAggregationBuilder ageAgg = AggregationBuilders.terms("ageAgg").field("age").size(10);
sourceBuilder.aggregation(ageAgg);
//1.3计算平均薪资
AvgAggregationBuilder balanceAvg = AggregationBuilders.avg("balanceAvg").field("balance");
sourceBuilder.aggregation(balanceAvg);
System.out.println("检索条件" + sourceBuilder.toString());
searchRequest.source(sourceBuilder);
//2.执行检索;
SearchResponse searchResponse = client.search(searchRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);
//3.分析结果 searchResponse
System.out.println(searchResponse.toString());
//3.1获取所有查到的数据
SearchHits hits = searchResponse.getHits();
SearchHit[] searchHits = hits.getHits();
for (SearchHit hit : searchHits) {
String string = hit.getSourceAsString();
Account account = JSON.parseObject(string, Account.class);
System.out.println("account:" + account);
}
//3.2获取这次检索到的分析信息
Aggregations aggregations = searchResponse.getAggregations();
//年龄
Terms ageAgg1 = aggregations.get("ageAgg");
for (Terms.Bucket bucket : ageAgg1.getBuckets()) {
String keyAsString = bucket.getKeyAsString();
System.out.println("年龄:" + keyAsString + "==>" + bucket.getDocCount());
}
//平均工资
Avg balanceAvg1 = aggregations.get("balanceAvg");
System.out.println("平均工资:" + balanceAvg1.getValue());
}
/**
* 测试存储数据到es
* 更新也可以
*/
@Test
public void indexData() throws IOException {
IndexRequest indexRequest = new IndexRequest("users");
//数据的ID
indexRequest.id("1");
// indexRequest.source("userName","zhangsan","age",18,"gender","男");
Users users = new Users();
users.setUserName("张三");
users.setAge(18);
users.setGender("男");
String jsonString = JSON.toJSONString(users);
//要保存的内容
indexRequest.source(jsonString, XContentType.JSON);
//执行保存操作
IndexResponse index = client.index(indexRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);
//提取有用的相应数据
System.out.println(index);
}
@Data
class Users {
private String userName;
private String gender;
private Integer age;
}
@ToString
@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
public void contextLoads() {
System.out.println(client);
}
}
输出:
年龄:38==>2
年龄:28==>1
年龄:32==>1
平均工资:25208.0
评论