1.5 Elasticsearch - Reste - client
1、9300 : TCP
Spring-data-elasticsearch: transport-api.jar
La version SpringBoot est différente, transport-api.jar est différent, il ne peut pas être adapté à la version es
7.x n'est plus adapté à l'utilisation, sera jeté après 8
2、9200 : HTTP
JestClient est non officiel et lent à mettre à jour
RestTemplate: les requêtes HTTP sont envoyées par défaut, et de nombreuses opérations d'ES doivent être encapsulées et gênantes
HttpClient: identique à ci-dessus
Elasticsearch-Rest-Client: Le RestClient officiel, qui encapsule les opérations ES et a une hiérarchie d'API claire
Enfin, choisissez Elasticsearch-Rest-Client (elasticsearch-rest-high-level-client)
1.5.1 Intégration SpringBoot
1 、 Pom.xml
<!-- 导入es的 rest-high-level-client -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.4.2</version>
</dependency>
Pourquoi importer ça? D'où vient cette configuration?
Site officiel: https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high-getting-started-maven.html
1.5.2 Configuration de la configuration
/**
* @author gcq
* @Create 2020-10-26
*
* 1、导入配置
* 2、编写配置,给容器注入一个RestHighLevelClient
* 3、参照API 官网进行开发
*/
@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;
builder = RestClient.builder(new HttpHost("192.168.56.10", 9200, "http"));
RestHighLevelClient client = new RestHighLevelClient(builder);
// RestHighLevelClient client = new RestHighLevelClient(
// RestClient.builder(
// new HttpHost("localhost", 9200, "http"),
// new HttpHost("localhost", 9201, "http")));
return client;
}
}
Site officiel: https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high-getting-started-initialization.html
1.5.3 Utilisation
Tester si l'injection est réussie
@Autowired
private RestHighLevelClient client;
@Test
public void contextLoads() {
System.out.println(client);
}
Tester si les données peuvent être ajoutées ou mises à jour
/**
* 添加或者更新
* @throws IOException
*/
@Test
public void indexData() throws IOException {
IndexRequest indexRequest = new IndexRequest("users");
User user = new User();
user.setAge(19);
user.setGender("男");
user.setUserName("张三");
String jsonString = JSON.toJSONString(user);
indexRequest.source(jsonString,XContentType.JSON);
// 执行操作
IndexResponse index = client.index(indexRequest, GulimallElasticsearchConfig.COMMON_OPTIONS);
// 提取有用的响应数据
System.out.println(index);
}
@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 searchData() throws IOException {
//创建检索请求
SearchRequest searchRequest = new SearchRequest();
//指定索引
searchRequest.indices("bank");
//指定dsl检索条件
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
// 1.1) 构造检索条件
// sourceBuilder.query();
// sourceBuilder.from();
// sourceBuilder.size();
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);
//执行检索
SearchResponse search = client.search(searchRequest, GulismallElasticSearchConfig.COMMON_OPTIONS);
//3.分析结果
System.out.println(search.toString());
//3.1获取素有查询到的数据
SearchHits hits = search.getHits();
SearchHit[] searchHits = hits.getHits();
for (SearchHit hit : searchHits) {
// hit.getIndex();hit.getPrimaryTerm();hit.getId();
Account account = JSON.parseObject(hit.getSourceAsString(), Account.class);
System.out.println("account:" + account);
}
//3.2获取这次检索到的分析信息
Aggregations aggregations = search.getAggregations();
// for (Aggregation aggregation : aggregations.asList()) {
// System.out.println("当前聚合:"+aggregation.getName());
// }
Terms ageAgg1 = aggregations.get("ageAgg");
for (Terms.Bucket bucket : ageAgg1.getBuckets()) {
System.out.println("年龄:" + bucket.getKeyAsString() + "==》" + bucket.getDocCount());
}
Avg balanceAvg1 = aggregations.get("balanceAvg");
balanceAvg1.getValue();
System.out.println("平均薪资:" + balanceAvg1.getValue());
}
Le sql récupéré dans kibana est le suivant