Elasticsearch不规则多边形区域查询

  1. 定义ES连接类
class ES_conn:
    def __init__(self):
        es_conf_psth = os.path.join(get_project_root_path(), 'config', 'db.conf')
        es_conf = Config(es_conf_psth)
        self.host = es_conf.get_option_val('es', 'host')
        self.port = es_conf.get_option_val('es', 'port')
        self.es = Elasticsearch(hosts=self.host.split(','), port=self.port)

其中self.es = Elasticsearch(hosts=self.host.split(‘,’), port=self.port)中,hosts参数接收的是一个字符串列表,例如[‘192.168.16.96’,‘192.168.16.97’,‘192.168.16.98’]等,端口是9200

  1. 创建一个带有geo_shape字段类型的索引。(仅执行一次)
es_conn = ES_conn()
index_name = "my_index"
    if es_conn.es.indices.exists(index=index_name):
        es_conn.es.indices.delete(index=index_name)

mappings = {
        "properties": {
            "location": {
                "type": "geo_shape"
            }
        }
    }
    
# 创建新的索引,并定义映射
es_conn.es.indices.create(index=index_name, mappings=mappings)
doc_body = {
	"objectid": "123456",
	"location": {
      "type": "point",
         "coordinates": [121.163214, 31.621541]
     }
}
# 插入一条数据
es_conn.es.index(index=index_name, id=1, body=doc_body) 
  1. 插入一条数据以后
    可以利用
mapping = es_conn.es.indices.get_mapping(index=index_name)
print(mapping)

来检查location字段是不是geo_shape类型

  1. 定义查询
s = Search(using=es_conn.es, index=index_name)
# 不规则多边形范围查询
s = s.filter('geo_shape', location={'relation': 'intersects',
                                    'shape': {'type': 'polygon', 'coordinates': coords}})
response = s.execute()

其中变量coords是一个三维list列表,用来表示一个多边形顶点坐标,如果你的多边形没有挖孔,那么第一维只有一个元素,否则有多个。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值