Elasticsearch is an open source search engine built on top of Apache Lucene™, a full-text search engine library. Lucene is arguably the most advanced, high-performance, full-featured search engine library available today — both open source and private.

Elasticsearch is also written in Java and uses Lucene internally for indexing and searching, but it is intended to make full text retrieval easy by hiding the complexity of Lucene and providing a simple and consistent RESTful API instead.

— Elasticsearch: The Definitive guide

Contents of this tutorial series:

  • Tutorial Demo (1)
  • Index Management Demo (2)
  • Document Management Demo (3)
  • Introductory tutorial search common functions Demo (four)
  • Introductory tutorial aggregation of common functions Demo (5)

1. Install the Elasticsearch

The official documentation

  1. From the website elastic. Co/downloads/elasticsearch to download the required version (this tutorial USES 7.9.2 version) elasticsearch

  2. Unzip and install Elasticsearch

  3. Running Elasticsearch.

    cdElasticsearch Installation directory. /bin/ElasticSearchCopy the code
  4. To verify that Elasticsearch is successfully started, visit http://localhost:9200/

  5. You are advised to use the Chrome plug-in ElasticSearch Head to manage, view, and query ES data

2. Create the Spring Boot Maven project

Github source: github.com/Mengzuozhu/…

Postman RESTful request Example of this project (can be imported to Postman)

The project structure of this tutorial:

3. The Maven references

  1. Elasticsearch key references:

            <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>
    
    Copy the code
  2. Pom file contents

    
            
    <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 - the 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 the 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>
    
    Copy the code

4. Configure elasticsearch

  1. Application.properties File contents

    server.port=8080
    
    # your es http url
    es.http.url=http://localhost:9200
    Copy the code
  2. Create a new ElasticSearchConfig. Java class file

    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(a) {
            return EsClientUtil.createRestHighLevelClient(esUrl);
        }
    
        @Bean
        IndicesClient indicesClient(a) {
            returnrestHighLevelClient().indices(); }}Copy the code
  3. EsClientUtil. Java tools

    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 newIllegalStateException(ex); }}}Copy the code