ElasticSearch 8.10.2 最新版 集成springboot,包括安全认证,使用Elasticsearch Java API Client,地理位置查询geoDistance

1、ElasticSearch 8.10.2 本地下载

下载地址:https://www.elastic.co/cn/downloads/past-releases/elasticsearch-8-10-2

2、运行

需要本地配置JAVA_HOME :jdk17

解压后进入文件夹:

双击elasticsearch.bat,即可运行

运行成功后,浏览器输入:http://localhost:9200/

成功则显示下面信息:

不成功可以看下一步(关闭安全认证)

3、安全认证

在根目录下打开config文件夹

修改elasticsearch.yml文件

修改参数:xpack.security.enabled

若为false,则不需要安全认证,访问以 http 开头

若为true,则需要安全认证,访问以 https 开头,同时访问需要输入账号和密码。

账号密码设置:(前提:xpack.security.enabled : true)

账号默认为:elastic

密码需要去设置,设置过程如下:

1、启动elasticsearch

2、在bin目录下启动cmd

敲击回车即可运行

然后输入:elasticsearch-reset-password -u elastic

输入y即可修改成功

密码自行保存下来。

3、重新启动elastisearch,即可成功修改密码。

4、集成springboot

pom依赖如下:

        <dependency>
            <groupId>org.elasticsearch.plugin</groupId>
            <artifactId>x-pack-sql-jdbc</artifactId>
            <version>8.10.2</version>
        </dependency>

        <dependency>
            <groupId>co.elastic.clients</groupId>
            <artifactId>elasticsearch-java</artifactId>
            <version>8.10.2</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>RELEASE</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.6.3</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba.fastjson2</groupId>
            <artifactId>fastjson2</artifactId>
            <version>2.0.15</version>
        </dependency>
        <dependency>
            <groupId>org.apache.lucene</groupId>
            <artifactId>lucene-core</artifactId>
            <version>8.8.0</version>
        </dependency>

配置yml文件

spring:
  elasticsearch:
    rest:
      # 是否启用es
      enable: true
      uris: localhost:9200
      host: localhost
      port: 9200
      username: elastic
      password: HtGJDGu8LHcxHKPKG8RL // 你自己设置的密码
      index: indexName
      crtName: http_ca.crt

将安全证书放在resourses下面

安全证书位于:elasticsearch-8.10.2\config\certs

配置config(参考大佬:Geng)

package com.mqy.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客户端配置
 * author:Geng
 */
@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());
    }

}

5、对index的操作

@RestController
public class ESController {

    @Autowired
    private ElasticsearchClient esClient;

    @Autowired
    private ElasticsearchTransport transport;

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

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

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

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

6、文档插入

@RestController
public class ESController {

    @Autowired
    private ElasticsearchClient esClient;

    @Autowired
    private ElasticsearchTransport transport;
    
    @GetMapping("/insert")
    public void insert() {
        
        Car car = new Car();

        try {
            esClient.create(s -> s
                    .index("car")      // 位于哪个索引
                    .id("10000")          // 唯一标识:id
                    .document(car)  // 映射实体
            );
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

7、查询

普通的查询官网文档上都有,这里不再演示

官网链接:https://www.elastic.co/guide/en/elasticsearch/client/java-api-client/current/indexing.html

地理位置的查询:,本人在各个平台没有找到对应的例子,这里重点展示:

@PostMapping("/init2")
    public void init2Elastic() throws Exception {

        // 地理查询
        SearchResponse<Object> response = esClient.search(s -> s
                        .index("car")
                        .query(q -> q
                                .bool(b -> b
                                        .filter(f -> f
                                                .geoDistance(g -> g       // 地理查询
                                                        .field("location")  
                                                        .distance("1km")      // 距离  
                                                        .location(new GeoLocation.Builder().latlon(new LatLonGeoLocation.Builder().lat(31.32729921232273).lon(118.8924004074097).build()).build()) // 当前经纬度
                                                )
                                        )

                                )
                        ),
                Object.class
        );
        System.out.println(response);
        List<Hit<Object>> hits = response.hits().hits();
        for (Hit<Object> hit: hits) {
            Object object = hit.source();
            System.out.println(object);
        }
    }

对应的https请求:

POST http://localhost:9200/car/_search
{
  "query": {
    "bool": {
      "filter": {
        "geo_distance": {
          "distance": "1km",
          "distance_type": "plane",
          "location": {
            "lon":  118.8924004074097,
            "lat":   31.32729921232273   
          }
        }
      }
    }
  }
}

感谢观看

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
对于Spring Boot集成Elasticsearch Java API Client,你可以按照以下步骤进行操作: 1. 首先,你需要在你的项目中添加Elasticsearch的依赖。可以在官方文档()中找到相关的依赖信息。 2. 接下来,你可以通过创建低级别的RestClient来连接到Elasticsearch。你可以使用以下代码片段来创建一个基于RestClient的传输对象: ```java RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build(); ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper()); ElasticsearchClient client = new ElasticsearchClient(transport); ``` 3. 一旦你建立了与Elasticsearch的连接,你就可以使用ElasticsearchClient来执行各种操作。比如,你可以使用以下代码来创建一个索引: ```java CreateIndexResponse createIndexResponse = client.indices().create(c -> c.index("newapi")); ``` 在这个例子中,"newapi"是你要创建的索引的名称。 所以,以上是使用Spring Boot集成Elasticsearch Java API Client的基本步骤。你可以根据你的具体需求进一步使用ElasticsearchAPI来完成其他操作。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [springboo整合elasticSearch8 java client api](https://blog.csdn.net/A434534658/article/details/125239480)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值