Elasticsearch-springboot

这篇具有很好参考价值的文章主要介绍了Elasticsearch-springboot。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

本文大多数代码摘抄自M.Arbre

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>3.1.1</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.xxx</groupId>
	<artifactId>elastic</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>elastic</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>17</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.elasticsearch.plugin</groupId>
			<artifactId>x-pack-sql-jdbc</artifactId>
			<version>8.7.1</version>
		</dependency>
		<dependency>
			<groupId>co.elastic.clients</groupId>
			<artifactId>elasticsearch-java</artifactId>
			<version>8.7.1</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.12.3</version>
		</dependency>
		<dependency>
			<groupId>jakarta.json</groupId>
			<artifactId>jakarta.json-api</artifactId>
			<version>2.0.1</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
			<version>3.1.1</version>
		</dependency>


		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-api</artifactId>
			<version>2.17.2</version>
		</dependency>

		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-core</artifactId>
			<version>2.17.2</version>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>1.18.28</version>
		</dependency>

	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

spring:
  elasticsearch:
    rest:
      # 是否启用es
      enable: true
      host: 9b4xxxxxxb829199076e3602b516.us-central1.gcp.cloud.es.io
      port: 443
      username: elastic
      password: 密码
      index: indexName
#      crtName: http_ca.crt

配置ElasticSearchConfig

package com.xxx.elastic.config;

import co.elastic.clients.elasticsearch.ElasticsearchAsyncClient;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
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.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.SSLContexts;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

//import javax.annotation.PostConstruct;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;

/**
 * es8的Java客户端配置
 */
@Configuration
//@Slf4j
public class ElasticSearchConfig {

    @Value("${spring.elasticsearch.rest.host}")
    private String host;
    @Value("${spring.elasticsearch.rest.enable}")
    private boolean enable;
    @Value("${spring.elasticsearch.rest.port}")
    private int port;
    @Value("${spring.elasticsearch.rest.username}")
    private String userName;
    @Value("${spring.elasticsearch.rest.password}")
    private String passWord;
//    @Value("${spring.elasticsearch.rest.crtName}")
//    private String tempCrtName;

    private static String crtName;

//    @PostConstruct
//    private void init() {
//        crtName = tempCrtName;
//    }

    /**
     * 解析配置的字符串,转为HttpHost对象数组
     *
     * @return
     */
    private HttpHost toHttpHost() {
        HttpHost httpHost = new HttpHost(host, port, "https");
        return httpHost;
    }

    /**
     * 同步客户端
     * @return
     * @throws Exception
     */
    @Bean
    public ElasticsearchClient clientBySync() throws Exception {
        ElasticsearchTransport transport = getElasticsearchTransport(userName, passWord, toHttpHost());
        return new ElasticsearchClient(transport);
    }

    /**
     * 异步客户端
     * @return
     * @throws Exception
     */
    @Bean
    public ElasticsearchAsyncClient clientByAsync() throws Exception {
        ElasticsearchTransport transport = getElasticsearchTransport(userName, passWord, toHttpHost());
        return new ElasticsearchAsyncClient(transport);
    }

    /**
     * 传输对象
     * @return
     * @throws Exception
     */
    @Bean
    public ElasticsearchTransport getTransport() throws Exception {
        return getElasticsearchTransport(userName, passWord, toHttpHost());
    }

    private static SSLContext buildSSLContext() {
        ClassPathResource resource = new ClassPathResource(crtName);
        SSLContext sslContext = null;
        try {
            CertificateFactory factory = CertificateFactory.getInstance("X.509");
            Certificate trustedCa;
            try (InputStream is = resource.getInputStream()) {
                trustedCa = factory.generateCertificate(is);
            }
            KeyStore trustStore = KeyStore.getInstance("pkcs12");
            trustStore.load(null, null);
            trustStore.setCertificateEntry("ca", trustedCa);
            SSLContextBuilder sslContextBuilder = SSLContexts.custom()
                    .loadTrustMaterial(trustStore, null);
            sslContext = sslContextBuilder.build();
        } catch (CertificateException | IOException | KeyStoreException | NoSuchAlgorithmException |
                 KeyManagementException e) {
//            log.error("ES连接认证失败", e);
        }

        return sslContext;
    }

    private static ElasticsearchTransport getElasticsearchTransport(String username, String passwd, HttpHost... hosts) {
        // 账号密码的配置
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, passwd));

        // 自签证书的设置,并且还包含了账号密码
        RestClientBuilder.HttpClientConfigCallback callback = httpAsyncClientBuilder -> httpAsyncClientBuilder
//                .setSSLContext(buildSSLContext())
                .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .setDefaultCredentialsProvider(credentialsProvider);

        // 用builder创建RestClient对象
        RestClient client = RestClient
                .builder(hosts)
                .setHttpClientConfigCallback(callback)
                .build();
        return new RestClientTransport(client, new JacksonJsonpMapper());
    }

}

import lombok.Data;

/**
 * @Date 2023/7/15 12:24
 */
@Data
public class User {

    private Integer Id;
    private String Username;
    private String Sex;
    private Integer Age;
}
package com.xxx.elastic.config;

import co.elastic.clients.elasticsearch.ElasticsearchAsyncClient;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.Result;
import co.elastic.clients.elasticsearch.core.search.HitsMetadata;
import co.elastic.clients.elasticsearch.indices.*;
import co.elastic.clients.transport.ElasticsearchTransport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
public class ESController {

    @Autowired
    private ElasticsearchClient syncClient;
    @Autowired
    private ElasticsearchAsyncClient asyncClient;

    @Autowired
    private ElasticsearchTransport transport;

    @GetMapping("/init")
    public void initElastic() throws Exception{
        //获取索引客户端对象
        ElasticsearchIndicesClient indices = syncClient.indices();

        //创建索引 采用构建器的方式构建(在创建之前需要先判断该索引是否存在)
        boolean exists = indices.exists(u -> u.index("userhahah")).value();
        if (exists) {
            System.out.println("该索引已存在!!");
        } else {
            CreateIndexResponse createIndexResponse = indices.create(c -> c.index("userhahah"));
            boolean acknowledged = createIndexResponse.acknowledged();
            System.out.println(acknowledged);
        }

        //查询索引
        GetIndexResponse getResponse = indices.get(g -> g.index("userhahah"));
        System.out.println("查询索引:"+getResponse);

        //删除索引
        DeleteIndexResponse deleteResponse = indices.delete(d -> d.index("userhahah"));
        System.out.println("删除索引:"+deleteResponse.acknowledged());
    }

//    创建文档
    @GetMapping("/initwd")
    public void initElasticwd() throws Exception{
        //获取索引客户端对象
        ElasticsearchIndicesClient indices = syncClient.indices();

        //创建文档
        User user = new User();
        user.setId(1001);
        user.setUsername("阿桃");
        user.setSex("男");
        user.setAge(26);

        Result result = syncClient.create(c -> c.index("userhahah").id("1001").document(user)).result();
        System.out.println("创建文档:"+result);

        //批量创建文档
        List<User> users = new ArrayList<>(); //假设有数据

        syncClient.bulk(b -> {   //批量创建操作
            users.forEach(u -> {   //遍历需要创建的数据
                b.operations(
                        o ->o.create(c -> c.index("userhahah").id(u.getId().toString()).document(u))
                );
            });
            return b;
        });

        //删除文档
        syncClient.delete(d -> d.index("userhahah").id("1001"));

        //查询文档
        HitsMetadata<Object> hits = syncClient.search(s -> {
            s.query(q -> q.match(
                    m -> m.field("username").query("阿桃")
            ));
            return s;
        }, Object.class).hits();

        transport.close(); //同步操作时需要关闭,异步时不需要关闭
    }
    @GetMapping("/initAsync")
    public void initAsyncElastic() throws Exception{
        //获取索引异步客户端对象
        ElasticsearchIndicesAsyncClient indices = asyncClient.indices();

        //异步调用无法直接获取操作反馈,只能通过回调进行判断
        //情况一
        indices.create(c -> c.index("newUser")).whenComplete(
                (response,error)->{
                    if(null != response){
                        System.out.println(response.acknowledged());
                    }else {
                        System.out.println(error);
                    }
                }
        );
        //情况二  thenApply中获取过acknowledged以后后续不用再获取了
        //thenApply是在创建完成后执行的,在whenComplete之前
        indices.create(c -> c.index("newUser")).thenApply(response -> response.acknowledged())
                .whenComplete(
                        (response,error)->{
                            if(response.equals(true)){
                                System.out.println(response);
                            }else {
                                System.out.println(error);
                            }
                        }
                );
    }

}


import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.GetResponse;
import co.elastic.clients.elasticsearch.core.IndexResponse;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.HighlightField;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.elasticsearch.core.search.HitsMetadata;
import co.elastic.clients.elasticsearch.indices.ElasticsearchIndicesClient;
import com.xxx.elastic.config.Product;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@SpringBootTest
class ElasticApplicationTests {
    @Autowired
    private ElasticsearchClient esClient;

    @Test
    void contextLoads() throws IOException {
        //获取索引客户端对象
//        esClient.indices().create(c -> c
//                .index("products")
//        );
        Product product = new Product("bk-1", "City-bike", 123);

        IndexResponse response = esClient.index(i -> i
                .index("products")
                .id(product.getSku())
                .document(product)
        );
        System.out.println("Indexed with version " + response.version());


        GetResponse<Product> getresponse = esClient.get(g -> g
                        .index("products")
                        .id(product.getSku()),
                Product.class
        );

        if (getresponse.found()) {
            Product getproduct = getresponse.source();
            System.out.println("Product name " + getproduct.getName());
        } else {
            System.out.println("Product not found");
        }
    }

    @Test
    void contextLoa() throws IOException {
        String searchText = "Updated";
        SearchResponse<Product> response = esClient.search(s -> s
                        .index("products")
                        .query(q -> q
                                .match(t -> t
                                        .field("name")
                                        .query(searchText)
                                )
                        ),
                Product.class
        );
//        HitsMetadata<Product> hits = response.hits();
        System.out.println("111");
    }

    @Test
    void contextLo() throws IOException {
        esClient.delete(d -> d.index("products").id("bk-1"));
    }

    @Test
    void context() throws IOException {
        Product product  = new Product("bk-1", "Updated name", 12356);
        esClient.update(u -> u
                        .index("products")
                        .id(product.getSku())
                        .doc(product)
                , Product.class);
    }
}

文章来源地址https://www.toymoban.com/news/detail-571292.html

到了这里,关于Elasticsearch-springboot的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 【Elasticsearch】Elasticsearch基本使用

    1.1 安装ES Elasticsearch下载地址 要求:JDK1.8+ Elasticsearch 与 Tomcat 类似,下载安装包后解压即可使用。我这里下载的是最新的 7.6.2 版本 解压后,首先设置跨域支持,后面可能用得上(连接es相关工具)。在 ./config/elasticsearch.yml 中添加跨域支持 在 bin 目录上方地址栏输入 cmd 打开终端输入

    2024年02月08日
    浏览(41)
  • Elasticsearch:提升 Elasticsearch 性能

    Elasticsearch 是为你的用户提供无缝搜索体验的不可或缺的工具。 在最近的 QCon 会议上,我遇到了很多的开发者。在他们的系统中,Elastic Stack 是不可缺少的工具,无论在搜索,可观测性或安全领域,Elastic Stack 都发挥着巨大的作用。我们在手机中常见的应用或者网站上的搜索基

    2023年04月08日
    浏览(35)
  • 【ElasticSearch01】ElasticSearch入门

    结构化数据 二维表等,保存到关系型数据库中例如mysql 非结构化数据 图像、视频、工作日志等,保存到Nosql数据库中,比如redis、mongodb中 半结构化数据 html、xml等保存到Nosql数据库中,比如redis、mongodb中 The Elastic Stack, 包括 Elasticsearch、 Kibana、 Beats 和 Logstash(也称为 ELK Stac

    2024年02月05日
    浏览(44)
  • 【Elasticsearch】初识elasticsearch

    目录 初识elasticsearch 1.1.了解ES 1.1.1.elasticsearch的作用 1.1.2.ELK技术栈 1.1.3.elasticsearch和lucene 1.1.4.为什么不是其他搜索技术? 1.1.5.总结 1.2.倒排索引 1.2.1.正向索引 1.2.2.倒排索引 1.2.3.正向和倒排 1.3.es的一些概念 1.3.1.文档和字段 1.3.2.索引和映射 1.3.3.mysql与elasticsearch 1.1.1.elasticsea

    2024年02月13日
    浏览(36)
  • 【ElasticSearch】ElasticSearch安装

    链接:https://pan.baidu.com/s/1FFUeglURINyY2ab-NzRZMw?pwd=snow 提取码:snow 1、上传ElasticSearch安装包至opt文件夹下(具体哪个文件夹根据自己喜好) 2、解压 3、创建普通用户 因为安全问题,Elasticsearch 不允许 root 用户直接运行,所以要创建新用户,在root用户中创建新用户,执行如下命令:

    2024年02月06日
    浏览(52)
  • 【ElasticSearch】ElasticSearch 内存设置原则

    由于ES构建基于lucene,而lucene设计强大之处在于lucene能够很好的利用操作系统内存来缓存索引数据,以提供快速的查询性能。lucene的索引文件segements是存储在单文件中的,并且不可变,对于OS来说,能够很友好地将索引文件保持在cache中,以便快速访问;因此,我们很有必要将一

    2024年02月14日
    浏览(37)
  • ElasticSearch笔记02-ElasticSearch入门

    ElasticSearch的官网,视频教程里用的Version是7.8.0,所以,我们也是用7.8.0版本的ElasticSearch。 下载地址:https://www.elastic.co/cn/downloads/past-releases#elasticsearch,然后搜索7.8.0版本即可。 按照视频里讲的,下载了Windows版本的ElasticSearch,当然,生产环境肯定是Linux版本的。 Windows版本的

    2024年02月09日
    浏览(62)
  • Elasticsearch:(二)1.安装Elasticsearch

    安装java环境 安装Elasticsearch 安装kibana 安装Elasticsearch-head插件  本节文章主要讲解 Elasticsearch的安装。  jdk兼容性:支持一览表 | Elastic 操作系统兼容性:支持一览表 | Elastic 自身产品兼容性: 支持一览表 | Elastic jdk版本选择 :最好选择 jdk1.8、jdk11(官方给出的Java 9、Java 10、

    2024年04月23日
    浏览(30)
  • 【elasticsearch】elasticsearch—API文档

    elasticsearch—API文档 创建文档 查询文档 修改文档 再次查询文档: 删除文档 批量修改文档 批量删除文档

    2024年02月06日
    浏览(32)
  • 【Elasticsearch】Elasticsearch官方测试数据

    原先的地址(已经失效了) :https://github.com/elastic/elasticsearch/blob/master/docs/src/test/resources/accounts.json?raw=true 备用地址 : https://github.com/elastic/elasticsearch/edit/7.5/docs/src/test/resources/accounts.json 下面是数据: {“index”:{“_id”:“1”}} {“account_number”:1,“balance”:39225,“firstname”:“

    2024年02月03日
    浏览(51)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包