史上最全的ElasticSearch系列之实战SpringBoot+ElasticSearch+HighLevelClient

本文涉及的产品
检索分析服务 Elasticsearch 版,2核4GB开发者规格 1个月
简介: 前言文本已收录至我的GitHub仓库,欢迎Star:github.com/bin39232820…种一棵树最好的时间是十年前,其次是现在

前言


文本已收录至我的GitHub仓库,欢迎Star:github.com/bin39232820…

种一棵树最好的时间是十年前,其次是现在

絮叨


昨天把简单的crud 给干完了,本来想讲讲原理的东西,但是我一想,大家都是才入门。就讲那写不好,所以我这边接着昨天的crud,把单机的搜索讲完,今天我们先讲讲Java的客户端HighLevelClient,其实我觉得应该很少人用它,但是我们公司用,所以我就写一下,明天再把JPA的方式也写一遍 下面是前面的系列文章


项目结构



pom 文件


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com</groupId>
  <artifactId>es</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>
  <name>es</name>
  <url>http://maven.apache.org</url>
  <properties>
    <java.version>1.8</java.version>
    <elasticsearch.version>6.4.3</elasticsearch.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
  <!-- Spring boot 父引用 -->
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.3.RELEASE</version>
  </parent>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
    </dependency>
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.54</version>
    </dependency>
    <dependency>
      <groupId>org.elasticsearch</groupId>
      <artifactId>elasticsearch</artifactId>
    </dependency>
    <dependency>
      <groupId>org.elasticsearch.client</groupId>
      <artifactId>elasticsearch-rest-high-level-client</artifactId>
      <version>6.4.3</version>
    </dependency>
  </dependencies>
</project>
复制代码


这里主要是设置项目的最基本的东西springboot环境 high level client 版本


config 连接es的配置


package com.es.config;
import java.util.ArrayList;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig.Builder;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestClientBuilder.HttpClientConfigCallback;
import org.elasticsearch.client.RestClientBuilder.RequestConfigCallback;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class EsConfiguration {
  private static String hosts = "192.168.62.145"; // 集群地址,多个用,隔开
  private static int port = 9200; // 使用的端口号
  private static String schema = "http"; // 使用的协议
  private static ArrayList<HttpHost> hostList = null;
  private static int connectTimeOut = 1000; // 连接超时时间
  private static int socketTimeOut = 30000; // 连接超时时间
  private static int connectionRequestTimeOut = 500; // 获取连接的超时时间
  private static int maxConnectNum = 100; // 最大连接数
  private static int maxConnectPerRoute = 100; // 最大路由连接数
  private RestClientBuilder builder;
  static {
    hostList = new ArrayList<>();
    String[] hostStrs = hosts.split(",");
    for (String host : hostStrs) {
      hostList.add(new HttpHost(host, port, schema));
    }
  }
  @Bean
  public RestHighLevelClient client() {
    builder = RestClient.builder(hostList.toArray(new HttpHost[0]));
    setConnectTimeOutConfig();
    setMutiConnectConfig();
    RestHighLevelClient client = new RestHighLevelClient(builder);
    return client;
  }
  // 异步httpclient的连接延时配置
  public void setConnectTimeOutConfig() {
    builder.setRequestConfigCallback(new RequestConfigCallback() {
      @Override
      public Builder customizeRequestConfig(Builder requestConfigBuilder) {
        requestConfigBuilder.setConnectTimeout(connectTimeOut);
        requestConfigBuilder.setSocketTimeout(socketTimeOut);
        requestConfigBuilder.setConnectionRequestTimeout(connectionRequestTimeOut);
        return requestConfigBuilder;
      }
    });
  }
  // 异步httpclient的连接数配置
  public void setMutiConnectConfig() {
    builder.setHttpClientConfigCallback(new HttpClientConfigCallback() {
      @Override
      public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
        httpClientBuilder.setMaxConnTotal(maxConnectNum);
        httpClientBuilder.setMaxConnPerRoute(maxConnectPerRoute);
        return httpClientBuilder;
      }
    });
  }
}
复制代码


创建一个启动类EsApp


package com.es;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class EsApp {
  public static void main(String[] args) {
    SpringApplication.run(EsApp.class, args);
  }
}
复制代码


创建一个bean


package com.es.bean;
public class Tests {
  private Long id;
  private String name;
  public Long getId() {
    return id;
  }
  public void setId(Long id) {
    this.id = id;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  @Override
  public String toString() {
    return "Tests [id=" + id + ", name=" + name + "]";
  }
}
复制代码


测试方法


创建一个索引

@Autowired
  private RestHighLevelClient client;
  /**
   * 创建索引
   * @param
   * @throws IOException
   */
  @Test
  public void createIndex() throws IOException {
    CreateIndexRequest request = new CreateIndexRequest("六脉神剑");
    CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
    System.out.println("createIndex: " + JSON.toJSONString(createIndexResponse));
  }
复制代码




判断索引是否存在

@Test
  public void existsIndex() throws IOException {
    GetIndexRequest request = new GetIndexRequest();
    request.indices("六脉神剑");
    boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
    System.out.println("existsIndex: " + exists);
  }
复制代码


往索引里面添加一个数据,也就是一个文档

@BeforeClass
  public static void before() {
    INDEX_TEST = "index_test";
    TYPE_TEST = "type_test";
    testsList = new ArrayList<>();
    for (int i = 0; i < 100; i++) {
      tests = new Tests();
      tests.setId(Long.valueOf(i));
      tests.setName("this is the test " + i);
      testsList.add(tests);
    }
  }
  @Test
  public void add() throws IOException {
    IndexRequest indexRequest = new IndexRequest("六脉神剑", "六脉神剑", tests.getId().toString());
    indexRequest.source(JSON.toJSONString(tests), XContentType.JSON);
    IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
    System.out.println("add: " + JSON.toJSONString(indexResponse));
  }
复制代码


这个beforeClass 是再测试方法之前把对象创建出来


查询一个文档

public void get() throws IOException {
    GetRequest getRequest = new GetRequest("六脉神剑", "六脉神剑", "99");
    GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
    System.out.println("get: " + JSON.toJSONString(getResponse));
  }
复制代码



更新记录信息

@Test
  public void update() throws IOException {
    tests.setName(tests.getName() + "updated");
    UpdateRequest request = new UpdateRequest("六脉神剑", "六脉神剑", tests.getId().toString());
    request.doc(JSON.toJSONString(tests), XContentType.JSON);
    UpdateResponse updateResponse = client.update(request, RequestOptions.DEFAULT);
    System.out.println("update: " + JSON.toJSONString(updateResponse));
  }
复制代码



搜索


@Test
  public void search() throws IOException {
    BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();
    boolBuilder.must(QueryBuilders.matchQuery("name", "is"));
    // boolBuilder.must(QueryBuilders.matchQuery("id", tests.getId().toString()));
    SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
    sourceBuilder.query(boolBuilder);
    sourceBuilder.from(0);
    sourceBuilder.size(100); // 获取记录数,默认10
    sourceBuilder.fetchSource(new String[] { "id", "name" }, new String[] {}); // 第一个是获取字段,第二个是过滤的字段,默认获取全部
    SearchRequest searchRequest = new SearchRequest("六脉神剑");
    searchRequest.types("六脉神剑");
    searchRequest.source(sourceBuilder);
    SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
    System.out.println("search: " + JSON.toJSONString(response));
    SearchHits hits = response.getHits();
    SearchHit[] searchHits = hits.getHits();
    for (SearchHit hit : searchHits) {
      System.out.println("search -> " + hit.getSourceAsString());
    }
  }
复制代码



批量操作

@Test
  public void bulk() throws IOException {
    // 批量增加
    BulkRequest bulkAddRequest = new BulkRequest();
    for (int i = 0; i < testsList.size(); i++) {
      tests = testsList.get(i);
      IndexRequest indexRequest = new IndexRequest(INDEX_TEST, TYPE_TEST, tests.getId().toString());
      indexRequest.source(JSON.toJSONString(tests), XContentType.JSON);
      bulkAddRequest.add(indexRequest);
    }
    BulkResponse bulkAddResponse = client.bulk(bulkAddRequest, RequestOptions.DEFAULT);
    System.out.println("bulkAdd: " + JSON.toJSONString(bulkAddResponse));
    search(INDEX_TEST, TYPE_TEST, "this");
    // 批量更新
    BulkRequest bulkUpdateRequest = new BulkRequest();
    for (int i = 0; i < testsList.size(); i++) {
      tests = testsList.get(i);
      tests.setName(tests.getName() + " updated");
      UpdateRequest updateRequest = new UpdateRequest(INDEX_TEST, TYPE_TEST, tests.getId().toString());
      updateRequest.doc(JSON.toJSONString(tests), XContentType.JSON);
      bulkUpdateRequest.add(updateRequest);
    }
    BulkResponse bulkUpdateResponse = client.bulk(bulkUpdateRequest, RequestOptions.DEFAULT);
    System.out.println("bulkUpdate: " + JSON.toJSONString(bulkUpdateResponse));
    search(INDEX_TEST, TYPE_TEST, "updated");
    // 批量删除
    BulkRequest bulkDeleteRequest = new BulkRequest();
    for (int i = 0; i < testsList.size(); i++) {
      tests = testsList.get(i);
      DeleteRequest deleteRequest = new DeleteRequest(INDEX_TEST, TYPE_TEST, tests.getId().toString());
      bulkDeleteRequest.add(deleteRequest);
    }
    BulkResponse bulkDeleteResponse = client.bulk(bulkDeleteRequest, RequestOptions.DEFAULT);
    System.out.println("bulkDelete: " + JSON.toJSONString(bulkDeleteResponse));
    search(INDEX_TEST, TYPE_TEST, "this");
  }
复制代码


结尾


今天就稍微讲了下这个的增删改查,只能说带大家入个门,后面的学习还是要靠自己了.

相关实践学习
使用阿里云Elasticsearch体验信息检索加速
通过创建登录阿里云Elasticsearch集群,使用DataWorks将MySQL数据同步至Elasticsearch,体验多条件检索效果,简单展示数据同步和信息检索加速的过程和操作。
ElasticSearch 入门精讲
ElasticSearch是一个开源的、基于Lucene的、分布式、高扩展、高实时的搜索与数据分析引擎。根据DB-Engines的排名显示,Elasticsearch是最受欢迎的企业搜索引擎,其次是Apache Solr(也是基于Lucene)。 ElasticSearch的实现原理主要分为以下几个步骤: 用户将数据提交到Elastic Search 数据库中 通过分词控制器去将对应的语句分词,将其权重和分词结果一并存入数据 当用户搜索数据时候,再根据权重将结果排名、打分 将返回结果呈现给用户 Elasticsearch可以用于搜索各种文档。它提供可扩展的搜索,具有接近实时的搜索,并支持多租户。
相关文章
|
4月前
|
JSON Java 网络架构
elasticsearch学习四:使用springboot整合 rest 进行搭建elasticsearch服务
这篇文章介绍了如何使用Spring Boot整合REST方式来搭建和操作Elasticsearch服务。
175 4
elasticsearch学习四:使用springboot整合 rest 进行搭建elasticsearch服务
|
3月前
|
JSON Java API
springboot集成ElasticSearch使用completion实现补全功能
springboot集成ElasticSearch使用completion实现补全功能
69 1
|
4月前
|
自然语言处理 Java API
Spring Boot 接入大模型实战:通义千问赋能智能应用快速构建
【10月更文挑战第23天】在人工智能(AI)技术飞速发展的今天,大模型如通义千问(阿里云推出的生成式对话引擎)等已成为推动智能应用创新的重要力量。然而,对于许多开发者而言,如何高效、便捷地接入这些大模型并构建出功能丰富的智能应用仍是一个挑战。
675 6
|
4月前
|
Web App开发 JavaScript Java
elasticsearch学习五:springboot整合 rest 操作elasticsearch的 实际案例操作,编写搜索的前后端,爬取京东数据到elasticsearch中。
这篇文章是关于如何使用Spring Boot整合Elasticsearch,并通过REST客户端操作Elasticsearch,实现一个简单的搜索前后端,以及如何爬取京东数据到Elasticsearch的案例教程。
311 0
elasticsearch学习五:springboot整合 rest 操作elasticsearch的 实际案例操作,编写搜索的前后端,爬取京东数据到elasticsearch中。
|
4月前
|
自然语言处理 Java Maven
elasticsearch学习二:使用springboot整合TransportClient 进行搭建elasticsearch服务
这篇博客介绍了如何使用Spring Boot整合TransportClient搭建Elasticsearch服务,包括项目创建、Maven依赖、业务代码和测试示例。
185 0
elasticsearch学习二:使用springboot整合TransportClient 进行搭建elasticsearch服务
|
5月前
|
缓存 NoSQL Java
Springboot实战——黑马点评之秒杀优化
【9月更文挑战第27天】在黑马点评项目中,秒杀功能的优化对提升系统性能和用户体验至关重要。本文提出了多项Spring Boot项目的秒杀优化策略,包括数据库优化(如索引和分库分表)、缓存优化(如Redis缓存和缓存预热)、并发控制(如乐观锁、悲观锁和分布式锁)以及异步处理(如消息队列和异步任务执行)。这些策略能有效提高秒杀功能的性能和稳定性,为用户提供更佳体验。
316 6
|
6月前
|
网络协议 Java API
SpringBoot整合Elasticsearch-Rest-Client、测试保存、复杂检索
这篇文章介绍了如何在SpringBoot中整合Elasticsearch-Rest-Client,并提供了保存数据和进行复杂检索的测试示例。
SpringBoot整合Elasticsearch-Rest-Client、测试保存、复杂检索
|
4月前
|
自然语言处理 搜索推荐 Java
SpringBoot 搜索引擎 海量数据 Elasticsearch-7 es上手指南 毫秒级查询 包括 版本选型、操作内容、结果截图(一)
SpringBoot 搜索引擎 海量数据 Elasticsearch-7 es上手指南 毫秒级查询 包括 版本选型、操作内容、结果截图
81 0
|
4月前
|
存储 自然语言处理 搜索推荐
SpringBoot 搜索引擎 海量数据 Elasticsearch-7 es上手指南 毫秒级查询 包括 版本选型、操作内容、结果截图(二)
SpringBoot 搜索引擎 海量数据 Elasticsearch-7 es上手指南 毫秒级查询 包括 版本选型、操作内容、结果截图(二)
68 0
|
6月前
|
Java API UED
【实战秘籍】Spring Boot开发者的福音:掌握网络防抖动,告别无效请求,提升用户体验!
【8月更文挑战第29天】网络防抖动技术能有效处理频繁触发的事件或请求,避免资源浪费,提升系统响应速度与用户体验。本文介绍如何在Spring Boot中实现防抖动,并提供代码示例。通过使用ScheduledExecutorService,可轻松实现延迟执行功能,确保仅在用户停止输入后才触发操作,大幅减少服务器负载。此外,还可利用`@Async`注解简化异步处理逻辑。防抖动是优化应用性能的关键策略,有助于打造高效稳定的软件系统。
94 2

热门文章

最新文章