Elasticsearch-经纬度查询(8.x)

目录

一、开发环境

二、pom文件

三、ES配置文件

四、ES相关字段

五、ES半径查询


ES的字段类型:geo_point,可以实现以一个点为中心的半径查询(geo_distance query)

ES地理位置查询:

  • 半径查询(geo_distance query)
  • 查询指定矩形内的数据(geo_bounding_box query)
  • 查询指定多边形内的数据(geo_polygon query)

官方文档:Geo queries | Elasticsearch Guide [8.14] | Elastic

本案例实现以某个点的经纬,查询半径查询,并计算出其他点和中心点的距离

一、开发环境

工具版本
JDK21
SpringBoot3.2.4
ElasticSearch8.13.2

二、pom文件

        <!-- Elasticsearch Java API Client -->
        <dependency>
            <groupId>co.elastic.clients</groupId>
            <artifactId>elasticsearch-java</artifactId>
            <version>8.13.2</version>
        </dependency>

三、ES配置文件

properties:

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.util.List;

/**
 * ES 配置属性
 *
 * @author meng
 * @date 2024-05-07
 */
@Data
@ConfigurationProperties(prefix = "es")
public class ElasticsearchProperties {
    /**
     * es 请求方式
     */
    private String scheme;
    /**
     * es 集群host ip 地址
     */
    private List<String> hosts;
    /**
     * es 账号
     */
    private String username;
    /**
     * es 密码
     */
    private String password;
    /**
     * es 连接超时时间
     */
    private Integer connectTimeOut;
    /**
     * es socket 连接超时时间
     */
    private Integer socketTimeOut;
    /**
     * es 请求超时时间
     */
    private Integer connectionRequestTimeOut;
    /**
     * es 最大连接数
     */
    private Integer maxConnectNum;
    /**
     * es 每个路由的最大连接数
     */
    private Integer maxConnectNumPerRoute;
}

config:

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 lombok.extern.slf4j.Slf4j;
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.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.net.ssl.SSLContext;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;

/**
 * ES 配置类,当 es.enable=true 时自动配置
 *
 * @author meng
 * @date 2024-05-07
 */
@Slf4j
@Configuration
@EnableConfigurationProperties(value = ElasticsearchProperties.class)
@ConditionalOnProperty(prefix = "es", name = "enable")
public class ElasticsearchConfig {

    @Bean(name = "ElasticsearchClient")
    public ElasticsearchClient initClient(ElasticsearchProperties elasticsearchProperties) {
        HttpHost[] esHosts = elasticsearchProperties.getHosts().stream().filter(StringUtils::isNotBlank).map(it -> {
            String[] split = it.split(":");
            return new HttpHost(split[0], Integer.parseInt(split[1]), elasticsearchProperties.getScheme());
        }).toArray(HttpHost[]::new);
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(elasticsearchProperties.getUsername(),
                        elasticsearchProperties.getPassword()));

        RestClientBuilder restClientBuilder = RestClient.builder(esHosts);
        // 连接延时配置
        restClientBuilder.setRequestConfigCallback(requestConfigBuilder -> {
            requestConfigBuilder.setConnectTimeout(elasticsearchProperties.getConnectTimeOut());
            requestConfigBuilder.setSocketTimeout(elasticsearchProperties.getSocketTimeOut());
            requestConfigBuilder.setConnectionRequestTimeout(elasticsearchProperties.getConnectionRequestTimeOut());
            return requestConfigBuilder;
        });
        // HttpClient 连接数配置
        restClientBuilder.setHttpClientConfigCallback(httpClientBuilder -> {
            httpClientBuilder.setMaxConnTotal(elasticsearchProperties.getMaxConnectNum());
            httpClientBuilder.setMaxConnPerRoute(elasticsearchProperties.getMaxConnectNumPerRoute());
            return httpClientBuilder;
        });
        // 设置keepalive时间
        restClientBuilder.setHttpClientConfigCallback(requestConfig ->
                requestConfig.setKeepAliveStrategy((response, context) -> Duration.ofMinutes(3).toMillis())
        );
        // 忽略HTTPS方式链接,SSL证书、主机名验证器
        restClientBuilder.setHttpClientConfigCallback(httpAsyncClientBuilder -> {
            httpAsyncClientBuilder.disableAuthCaching();
            httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            try {
                // 创建一个信任所有证书的 TrustStrategy 策略
                TrustStrategy acceptTrustStrategy = (chain, authType) -> true;
                // 使用 SSLContextBuilder 创建 SSLContext
                SSLContext sslContext = SSLContextBuilder.create().loadTrustMaterial(null, acceptTrustStrategy).build();
                httpAsyncClientBuilder.setSSLContext(sslContext);
            } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
                e.printStackTrace();
            }
            // 忽略主机名验证
            httpAsyncClientBuilder.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE);
            return httpAsyncClientBuilder;
        });
        RestClient restClient = restClientBuilder.build();
        // 使用Jackson映射器创建传输层
        ElasticsearchTransport transport = new RestClientTransport(
                restClient, new JacksonJsonpMapper()
        );
        ElasticsearchClient client = new ElasticsearchClient(transport);
        return client;
    }

}

四、ES相关字段

五、ES半径查询

具体查询对象,可自行定义,本方法只提供思路,莫直接粘贴使用

	@Resource
    private ElasticsearchClient esClient;

	/**
	 * 功能描述: 根据经纬度判断十米内是否有poi数据
	 *
	 * @Param: [request]
	 * @Author: meng
	 * @Date: 2024/6/6 19:57
	 */
	private PoiDTO getPoiNear(PoiRequest request) {
		if (Objects.isNull(request.getLongitude()) && Objects.isNull(request.getLatitude())) {
			return null;
		}
		// 中心点查询
		GeoLocation geoLocation = new GeoLocation.Builder().latlon(
				l -> l.lon(request.getLongitude().doubleValue()).lat(request.getLatitude().doubleValue())).build();
		GeoDistanceQuery geoDistanceQuery = GeoDistanceQuery.of(
				geoDis -> geoDis.field(PoiIndexConstant.LOCATION).location(geoLocation)
						.distance(PoiIndexConstant.DISTANCE).distanceType(GeoDistanceType.Arc));
		// 排序
		List<SortOptions> sorts = new ArrayList<>();
		// 距离排序 米
		GeoDistanceSort geoDistanceSort = GeoDistanceSort.of(
				geoDis -> geoDis.field(PoiIndexConstant.LOCATION).location(geoLocation).order(SortOrder.Asc)
						.unit(DistanceUnit.Meters));
		SortOptions sortOptions = SortOptions.of(sort -> sort.geoDistance(geoDistanceSort));
		sorts.add(sortOptions);
		SearchRequest.Builder searchRequestBuilder = new SearchRequest.Builder();
		searchRequestBuilder.index(PoiIndexConstant.INDEX_READ)
				.query(query -> query.bool(builder -> builder.filter(f -> f.geoDistance(geoDistanceQuery)))).sort(sorts)
				.size(CommonConstant.DEFAULT_NUM);
		// ES查询
		SearchRequest searchRequest = searchRequestBuilder.build();
		log.info("getPoiNear query:{}", searchRequest.toString());
		try {
            SearchResponse<PoiIndex> searchResponse = esClient.search(searchRequest, PoiIndex.class);
            // 未查到数据
			if (Objects.nonNull(searchResponse.hits().total()) && searchResponse.hits().total().value() == 0) {
				return null;
			}
			for (Hit<PoiIndex> hit : searchResponse.hits().hits()) {
				if (ObjectUtil.isNotNull(hit.source())) {
					PoiIndex poiIndex = BeanUtil.copyProperties(hit.source(), PoiIndex.class);
					return BeanUtil.copyProperties(poiIndex, PoiDTO.class);
				}
			}
        } catch (Exception e) {
            log.error("es searchRequest Exception:", e);
            throw new ServiceException("searchRequest Exception");
        }
		return null;
	}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/706756.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

现代易货模式:重塑物品价值,引领交换新潮流

在日益繁荣的现代社会&#xff0c;物品交换文化正逐渐兴起&#xff0c;一种新型的交易模式——现代易货模式&#xff0c;正在成为市场的新宠。它不仅是对传统“以物易物”模式的现代化演绎&#xff0c;更是对物品价值再认识和交换方式创新的体现。 现代易货模式&#xff0c;简言…

【表单视图】-卡片视图支持统计设置

06/05 主要更新模块概览 统计设置 快捷回复 背景设置 帮助中心 01 表单管理 1.1 【表单视图】-卡片视图新增统计设置 说明&#xff1a; 在卡片视图中成功新增了统计功能和统计效果。现在&#xff0c;用户无需额外操作&#xff0c;即可在卡片视图状态下直接清晰地看到需求…

STM32开发过程中碰到的问题总结 - 1

文章目录 前言1. 怎么生成keil下可以使用的文件和gcc下编译使用的makefile2. STM32的时钟树3.怎么查看keil5下的编译工具链用的是哪个4. Arm编译工具链和GCC编译工具链有什么区别吗&#xff1f;5. 怎么查看Linux虚拟机是x86的还是aarch646. 怎么下载gcc-arm的编译工具链7.怎么修…

推挽与开漏输出

一般来说&#xff0c;微控制器的引脚都会有一个驱动电路&#xff0c;可以配置不同类型的数字和模拟电路接口。输出模式一般会有推挽与开漏输出。 推挽输出 推挽输出&#xff08;Push-Pull Output&#xff09;&#xff0c;故名思意能输出两种电平&#xff0c;一种是推&#xf…

天降流量于雀巢?元老品牌如何创新营销策略焕新生

大家最近有看到“南京阿姨手冲咖啡”的视频吗&#xff1f;三条雀巢速溶咖啡入杯&#xff0c;当面加水手冲&#xff0c;十元一份售出&#xff0c;如此朴实的售卖方式迅速在网络上走红。而面对这一波天降的热度&#xff0c;雀巢咖啡迅速做出了回应&#xff0c;品牌组特地去到了阿…

君子签帮助物流组织打造线上签约平台,助力简化成本,高效运转

各类物流组织日常业务可能涉及“企业入驻、快递、整车运输、货运、仓储、供应链等”多种类型&#xff0c;各个环节都存在大量的文件/单据签署&#xff0c;网点、客户、司机、收货人遍布全国各地&#xff0c;复杂的签署需求&#xff0c;以及庞大的签字、用印需求&#xff0c;让各…

2.6数据报与虚电路

数据报 当作为通信子网用户的端系统要发送一个报文时&#xff0c;在端系统中实现的高层协议先把报文拆成若干个带有序号的数据单元&#xff0c;并在网络层加上地址等控制信息后形成数据报分组(即网络层PDU)中间结点存储分组一段很短的时间&#xff0c;找到最佳的路由后&#x…

讯飞有一个可以根据描述文本自动生成PPT的AI接口,有趣

文档&#xff1a;https://www.xfyun.cn/doc/spark/PPTGeneration.html 价格方面提供了免费1000点的额度&#xff0c;生成一次是10点&#xff0c;正好100次&#xff0c;如果要购买的话最低要购买1344元的&#xff0c;没有按量付费的模式&#xff0c;个人小开发者可买不起。 让我…

无线网络与物联网技术[1]之近距离无线通信技术

无线网络与物联网技术 近距离无线通信技术WIFIWi-Fi的协议标准Wi-Fi的信道Wi-Fi技术的术语Wi-Fi的组网技术Ad-hoc模式无线接入点-APAP&#xff1a;FAT AP vs FIT AP Wi-Fi的特点与应用Wi-Fi的安全技术 Bluetooth蓝牙技术概论蓝牙的技术协议蓝牙的组网技术微微网piconet(了解)散…

安装操作系统1-Win10版本介绍及硬件要求

注意&#xff1a;安装系统&#xff0c;首先弄清有哪些版本及所需硬件环境。 1.Win10有哪些版本 微软将 Win10为以下7个版本&#xff1a; Windows 10 家庭版&#xff08;Home&#xff09; 面向所有普通用户&#xff0c;提供Win 10的基本功能。此版本适合个人家庭用户使用&am…

ATFX汇市:美国5月通胀率回落,降息预期刺激黄金走高

ATFX汇市&#xff1a;据美国劳工部发布的最新数据&#xff0c;美国5月核心CPI年率最新值3.4%&#xff0c;低于前值3.6%&#xff1b;名义CPI年率最新值3.3%&#xff0c;低于前值3.4%。核心CPI年率和名义CPI年率双双下降&#xff0c;超出此前市场预期&#xff08;预期为整体保持不…

App自动化之dom结构和元素定位方式(包含滑动列表定位)

DOM结构 先来看几个名词和解释&#xff1a; dom: Document Object Model 文档对象模型 dom应用: 最早应用于html和js的交互。界面的结构化描述&#xff0c; 常见的格式为html、xml。核心元素为节点和属性 xpath: xml路径语言&#xff0c;用于xml 中的节点定位&#xff0c;X…

postman教程-20-Newman安装入门

上一小节我们学习了Postman mock测试的方法&#xff0c;本小节我们讲解一下Postman Newman的安装方法。 Newman是Postman团队开发的一个命令行工具&#xff0c;它允许用户通过命令行接口&#xff08;CLI&#xff09;运行Postman集合&#xff08;Collections&#xff09;和环境…

STM32程序启动过程

&#xff08;1&#xff09;首先对栈和堆的大小进行定义&#xff0c;并在代码区的起始处建立中断向量表&#xff0c;其第一个表项是栈顶地址&#xff08;32位&#xff09;&#xff0c;第二个表项是复位中断服务入口地址&#xff1b; &#xff08;2&#xff09;然后执行复位中断&…

关于FPGA对 DDR4 (MT40A256M16)的读写控制 I

关于FPGA对 DDR4 &#xff08;MT40A256M16&#xff09;的读写控制 I 语言 &#xff1a;Verilg HDL EDA工具&#xff1a;ISE、Vivado 关于FPGA对 DDR4 &#xff08;MT40A256M16&#xff09;的读写控制 I一、引言二、DDR4的特性&#xff08;MT40A256M16&#xff09;&#xff08;1…

QML学习十九:ttf字体库使用

一、前言 在使用QML时&#xff0c;常常自定义按钮&#xff0c;按钮上有显示个图标&#xff0c;其实&#xff0c;那不是图标&#xff0c;是文本&#xff0c;如何显示&#xff1f; 本篇记录&#xff0c;如何导入阿里巴巴字体库&#xff0c;并调用显示。 二、阿里巴巴字体库下载…

少样本学习元学习

基本概念 首先是机器学习&#xff1a; 然后&#xff0c;什么是元学习&#xff08;what is meta learning?) 之前&#xff0c;Component都是让人自己设置的。在Meta Learning中&#xff0c;我们期望它能够自己学出来。 不同的meta learning方法就是想办法去学learning algori…

Vue3【二十一】Vue 路由模式(createWebHashHistory /createWebHistory )和RouterLink写法

Vue3【二十一】Vue 路由模式&#xff08;createWebHashHistory /createWebHistory &#xff09;和RouterLink写法 Vue3【二十一】Vue 路由模式和普通组件目录结构 createWebHistory history模式&#xff1a;url不带#号&#xff0c;需要后端做url适配 适合销售项目 利于seo crea…

Spring Boot整合hibernate-validator实现数据校验

文章目录 概念基本概念常用校验注解 前置内容整合Hibernate Validator快速入门优雅处理参数校验异常其余注解校验自定义校验注解 参考来源 概念 基本概念 Hibernate Validator 是一个参数校验框架&#xff0c;可以非常方便地帮助我们校验应用程序的入参&#xff0c;实现了参数…

零一科技Yi-VL 6B视觉大模型环境搭建推理

引子 最近看新闻博客说零一科技的Yi-VL-Plus视觉大模型效果很不错&#xff0c;那就想着尝尝鲜。这是第四篇关于视觉大模型的博客。之前有写过一篇零一科技的chat大模型零一科技Yi-34B Chat大模型环境搭建&推理_python部署大模型yi-34b-chat-CSDN博客&#xff0c;感兴趣的童…