Elasticsearch Java 从入门到出家 教程 Demo (一)

1,333 阅读2分钟

Elasticsearch 是一个开源的搜索引擎,建立在一个全文搜索引擎库 Apache Lucene™ 基础之上。 Lucene 可以说是当下最先进、高性能、全功能的搜索引擎库—无论是开源还是私有。

Elasticsearch 也是使用 Java 编写的,它的内部使用 Lucene 做索引与搜索,但是它的目的是使全文检索变得简单, 通过隐藏 Lucene 的复杂性,取而代之的提供一套简单一致的 RESTful API。

​ ——Elasticsearch: 权威指南

本教程系列目录:

1. 安装Elasticsearch

官方文档

  1. 从官网 elastic.co/downloads/elasticsearch 下载所需版本(本教程使用7.9.2版本)的 Elasticsearch

  2. 解压安装Elasticsearch, 安装说明

  3. 运行Elasticsearch:

    cd elasticsearch安装目录
    ./bin/elasticsearch
    
  4. 验证Elasticsearch 是否启动成功:浏览器访问 http://localhost:9200/

  5. 推荐使用Chrome插件ElasticSearch Head,进行ES数据的管理、查看与查询等常用操作

2. 新建Spring Boot Maven项目

Github源码:github.com/Mengzuozhu/…

本项目Postman RESTful请求示例(可导入到Postman)

本教程的项目结构:

3. Maven引用

  1. elasticsearch关键引用:

            <dependency>
                <groupId>org.elasticsearch</groupId>
                <artifactId>elasticsearch</artifactId>
                <version>${elasticsearch.version}</version>
            </dependency>
            <dependency>
                <groupId>org.elasticsearch.client</groupId>
                <artifactId>elasticsearch-rest-high-level-client</artifactId>
                <version>${elasticsearch.version}</version>
            </dependency>
    
    
  2. pom文件内容

    <?xml version="1.0" encoding="UTF-8"?>
    <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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.3.4.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>com.mzz</groupId>
        <artifactId>es-demo</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>es-demo</name>
        <description>ES Demo</description>
    
        <properties>
            <java.version>1.8</java.version>
            <elasticsearch.version>7.9.2</elasticsearch.version>
            <commons-collections4.version>4.4</commons-collections4.version>
            <fastjson.version>1.2.68</fastjson.version>
            <guava.version>30.1-jre</guava.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-configuration-processor</artifactId>
                <optional>true</optional>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <optional>true</optional>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
                <exclusions>
                    <exclusion>
                        <artifactId>assertj-core</artifactId>
                        <groupId>org.assertj</groupId>
                    </exclusion>
                    <exclusion>
                        <artifactId>junit-vintage-engine</artifactId>
                        <groupId>org.junit.vintage</groupId>
                    </exclusion>
                </exclusions>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-aop</artifactId>
            </dependency>
            <dependency>
                <groupId>org.elasticsearch</groupId>
                <artifactId>elasticsearch</artifactId>
                <version>${elasticsearch.version}</version>
            </dependency>
            <dependency>
                <groupId>org.elasticsearch.client</groupId>
                <artifactId>elasticsearch-rest-high-level-client</artifactId>
                <version>${elasticsearch.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.commons</groupId>
                <artifactId>commons-lang3</artifactId>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
                <version>${fastjson.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.commons</groupId>
                <artifactId>commons-collections4</artifactId>
                <version>${commons-collections4.version}</version>
            </dependency>
            <dependency>
                <groupId>com.google.guava</groupId>
                <artifactId>guava</artifactId>
                <version>${guava.version}</version>
            </dependency>
    
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
    </project>
    
    

4. 配置elasticsearch

  1. application.properties文件内容

    server.port=8080
    
    # your es http url
    es.http.url=http://localhost:9200
    
  2. 新建ElasticsearchConfig.java类文件

    package com.mzz.esdemo.config;
    
    import com.mzz.esdemo.common.util.EsClientUtil;
    import org.elasticsearch.client.IndicesClient;
    import org.elasticsearch.client.RestHighLevelClient;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    /**
     * The type Elasticsearch config.
     *
     * @author Zero
     */
    @Configuration
    public class ElasticsearchConfig {
        @Value("${es.http.url}")
        private String esUrl;
    
        @Bean
        RestHighLevelClient restHighLevelClient() {
            return EsClientUtil.createRestHighLevelClient(esUrl);
        }
    
        @Bean
        IndicesClient indicesClient() {
            return restHighLevelClient().indices();
        }
    }
    
    
  3. EsClientUtil.java工具类

    package com.mzz.esdemo.common.util;
    
    import org.apache.commons.lang3.StringUtils;
    import org.apache.http.HttpHost;
    import org.apache.http.auth.AuthScope;
    import org.apache.http.auth.UsernamePasswordCredentials;
    import org.apache.http.client.CredentialsProvider;
    import org.apache.http.impl.client.BasicCredentialsProvider;
    import org.elasticsearch.client.RestClient;
    import org.elasticsearch.client.RestClientBuilder;
    import org.elasticsearch.client.RestHighLevelClient;
    
    import java.net.URI;
    import java.net.URISyntaxException;
    
    /**
     * The type Es client util.
     *
     * @author Zero
     */
    public class EsClientUtil {
    
        /**
         * Create rest high level client.
         *
         * @param esUrl the es url
         * @return the rest high level client
         */
        public static RestHighLevelClient createRestHighLevelClient(String esUrl) {
            return new RestHighLevelClient(getRestClientBuilder(esUrl));
        }
    
        /**
         * Create rest high level client.
         *
         * @param esIp   the es ip
         * @param esPort the es port
         * @return the rest high level client
         */
        public static RestHighLevelClient createRestHighLevelClient(String esIp, Integer esPort) {
            return new RestHighLevelClient(RestClient.builder(new HttpHost(esIp, esPort, "http")));
        }
    
        /**
         * Create rest high level client.
         *
         * @param esUrl    the es url
         * @param userName the user name
         * @param password the password
         * @return the rest high level client
         */
        public static RestHighLevelClient createRestHighLevelClient(String esUrl, String userName, String password) {
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));
            RestClientBuilder restClientBuilder = getRestClientBuilder(esUrl)
                    .setHttpClientConfigCallback(httpClientBuilder -> {
                        httpClientBuilder.disableAuthCaching();
                        return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                    });
            return new RestHighLevelClient(restClientBuilder);
        }
    
        /**
         * Create rest high level client with keep alive.
         *
         * @param esUrl     the es url
         * @param keepAlive the keep alive
         * @return the rest high level client
         */
        public static RestHighLevelClient createRestHighLevelClientWithKeepAlive(String esUrl, Long keepAlive) {
            RestClientBuilder clientBuilder = getRestClientBuilder(esUrl)
                    .setHttpClientConfigCallback(requestConfig ->
                            requestConfig.setKeepAliveStrategy((response, context) -> keepAlive));
            return new RestHighLevelClient(clientBuilder);
        }
    
        /**
         * Gets rest client builder.
         *
         * @param esUrl the es url
         * @return the rest client builder
         */
        public static RestClientBuilder getRestClientBuilder(String esUrl) {
            return RestClient.builder(createHttpHost(URI.create(esUrl)));
        }
    
        /**
         * Create http host.
         *
         * @param uri the uri
         * @return the http host
         */
        public static HttpHost createHttpHost(URI uri) {
            if (StringUtils.isEmpty(uri.getUserInfo())) {
                return HttpHost.create(uri.toString());
            }
            try {
                return HttpHost.create(new URI(uri.getScheme(), null, uri.getHost(), uri.getPort(), uri.getPath(),
                        uri.getQuery(), uri.getFragment()).toString());
            } catch (URISyntaxException ex) {
                throw new IllegalStateException(ex);
            }
        }
    }