首页 > 编程语言 >python 操作 ES 一、基础操作

python 操作 ES 一、基础操作

时间:2023-02-23 18:23:47浏览次数:33  
标签:body index python doc ES print 操作 es w2

示例代码环境 python:3.8  es:7.8.0
环境安装 pip install elasticsearch==7.8.0
from elasticsearch import Elasticsearch



#1、创建ES对象,创建连接
es = Elasticsearch(['127.0.0.1:9200'],ignore=[400, 405, 502])
print('---------------1--------------------------')

# 2、创建索引index:索引的名字,ignore:状态码
result=es.indices.create(index="user",ignore=400)
print(result)
print('---------------2--------------------------')

# 3、删除索引
result = es.indices.delete(index='user', ignore=[400, 404])
print(result)
print('-----------------3------------------------')


#4、新增
#es.index,向指定索引添加或更新文档,如果索引不存在,首先会创建该索引,然后再执行添加或者更新操作。
print(es.index(index='w2', doc_type='_doc', id='4', body={"name":"可可", "age": 18}))    # 正常
print(es.index(index='w2', doc_type='_doc', id=5, body={"name":"卡卡西", "age":22}))     # 正常
print(es.index(index='w2', doc_type='_doc', body={"name": "鸣人", "age": 22}))  # 可以不指定id,默认生成一个id
print('-----------------4------------------------')

#5、查询
#5.1  es.get,查询索引中指定文档 主键查询
print(es.get(index='w2', doc_type='_doc', id=5))
#print(es.get(index='w2', doc_type='doc'))  # TypeError: get() missing 1 required positional argument: 'id'
#print(es.get(index='w2',  id=5))  # TypeError: get() missing 1 required positional argument: 'doc_type'
print('-----------------5------------------------')

#5.2 es.search,执行搜索查询并获取与查询匹配的搜索匹配。这个用的最多,可以跟复杂的查询条件。
'''
    index要搜索的以逗号分隔的索引名称列表; 使用_all 或空字符串对所有索引执行操作。
    body 使用Query DSL(QueryDomain Specific Language查询表达式)的搜索定义。
    _source  返回指定字段。
    excludes  返回的所有字段中,排除哪些字段。
    includes从_source字段中提取和返回的字段列表,跟_source差不多
'''

#一般查询
body = {
  "query": {
    "match": {
       "age": 22
    }
  }
}
print(es.search(index='w2',   body=body))
#查询所有
body = {
  "query": {
    "match_all": {}
  }
}
print(es.search(index='w2',   body=body))
# #与上一条等价
print(es.search(index='w2',   body={"query": {"match":{"age": 18}}} ) )
# # 结果字段过滤
print(es.search(index='w2',   body={"query": {"match":{"age": 18}}},_source=['name', 'age']))
# # 结果字段过滤
print(es.search(index='w2',   body={"query": {"match":{"age": 18}}},_source=['name']))

#使用includes 指定返回字段
body1 ={
  "_source": {
    "includes": ["age"]
     },
  "query": {
      "match": {
          "age": 18
      }
  }
}
print(es.search(index='w2',  body=body1))

#excludes 返回的所有字段中,排除哪些字段
body2 ={
  "_source": {
    "excludes": ["age"]
     },
  "query": {
      "match": {
          "age": 18
      }
  }
}
print(es.search(index='w2',  body=body2))


#测试 模糊查询 name只输入“卡” 可以查出name=“卡卡西”的数据
body3 ={
  "query": {
      "match": {
          "name": "卡"
      }
  }
}
print(es.search(index='w2',  body=body3))

#5.3 get_source,通过索引、类型和ID获取文档的来源,其实,直接返回想要的字典。 对比如下结果
print(es.get(index='w2', doc_type='_doc', id=5))
print(es.get_source(index='w2',  id=5))


#5.4 es.count,执行查询并获取该查询的匹配数。比如查询年龄是18的文档。
body4 = {
    "query": {
        "match": {
            "age": 18
        }
    }
}
print(es.count(index='w2',  body=body4))  # {'count': 1, '_shards': {'total': 5, 'successful': 5, 'skipped': 0, 'failed': 0}}
print(es.count(index='w2',  body=body4)['count'])  # 1

# 6 es.delete,删除指定的文档。比如删除文章id为4的文档,但不能删除索引,如果想要删除索引,还需要es.indices.delete来处理
print(es.index(index='w2', doc_type='_doc', id=6, body={"name":"yc", "age": 18}))
print(es.get(index='w2', doc_type='_doc', id=6))
print(es.delete(index='w2',  id=6))
print(es.get(index='w2', doc_type='_doc', id=6)) #查询不存在的会报错

# 7 es.delete_by_query,删除与查询匹配的所有文档。
'''
    index 要搜索的以逗号分隔的索引名称列表; 使用_all 或空字符串对所有索引执行操作。
    body 使用Query DSL的搜索定义。
'''
#print(es.search(index='w2'))
print(es.delete_by_query(index='w2',   body={"query": {"match":{"age": 22}}}))
print(es.search(index='w2'))

# 8 es.exists,查询elasticsearch中是否存在指定的文档,返回一个布尔值。
print(es.exists(index='w2',   id='4'))

# 9 es.info,获取当前集群的基本信息。
print(es.info())

# 10 es.ping,如果群集已启动,则返回True,否则返回False。
print(es.ping())

 

标签:body,index,python,doc,ES,print,操作,es,w2
From: https://www.cnblogs.com/yclh/p/17149002.html

相关文章

  • Kubernetes Ingress 原理
    阅读本文前提条件:理解k8sService的大致原理;会照猫画虎地使用Ingress。原理概述Service可以供内部程序使用,若不在路由设备上配置相应规则,外部节点无法访问Service......
  • python 操作 ES 二、mappings
    环境python:3.8es:7.8.0环境安装pipinstallelasticsearch==7.8.0  fromelasticsearchimportElasticsearch#环境python:3.8es:7.8.0#环境安装#pipinstal......
  • docker 操作笔记
    1.Docker创建ubuntu系统更换apt-get源创建Dockerfile并且更新apt源在Dockerfile中添加如下两句代码:RUNsed-is@/archive.ubuntu.com/@/mirrors.aliyun.com/@g/et......
  • python next() iter()使用
    说明:next()、iter()这两个函数一般配套使用。下面先介绍用法,后说明用途。用法:iter(object):生成可迭代对象的迭代器;object必须是可迭代对象,比如list、tuple、dict等;next(i......
  • SSRF Server-Side Request Forgery(服务器端请求伪造)
    什么是SSRF?犹如其名,SSRF(Server-SideRequestForgery)服务端请求伪造,攻击者可以控制服务器返回的页面,借用服务器的权限无访问无权限的页面。这是一个允许恶意用户导致......
  • k8s部署wordpress
    nginxnginx.confserver{listen80;server_namelocalhost;location/{root/apps/nginx/wordpress;indexindex.phpind......
  • 银河麒麟V10系统的 postgresql/postgis完整部署
    一、posgresql部署1、安装前可以先进行用户以及用户组的配置,方便后面进行授权(通过编译安装也需要,后续步骤会体现)。用户配置#新增用户组groupaddpostgres#创建用户......
  • cesium 颜色赋值
     constline2=newCesium.Primitive({      geometryInstances:newCesium.GeometryInstance({        geometry:newCesium.Polyline......
  • keycloak~LB到Ingress再到K8s的路径问题
    问题的产生对于我们的容器化部署项目keycloak来说,当它从云端负载均衡LB直接通过NodePort转发到keycloak时,没有任务问题,一切正常;缺点就是,运维人员要维护一大批端口,哪个端......
  • vue 中对监听esc事件,退出全屏的问题解决
    vue的项目中使用了h5的全屏API,在使用esc键退出全屏时,默认调用“document.exitFullScreen()”直接退出,想要做监听并设置业务,需要监听屏幕size变化来出发事件mounte......