zoukankan      html  css  js  c++  java
  • python对接elasticsearch的基本操作

    一.关于集群的基本操作

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    # author tom
    from elasticsearch import Elasticsearch
    from pprint import pprint
    
    # 连接es,直接传一个ip字符串参数也可以,他会帮你封装成列表的
    es_host = 'XXX.XX.XX.XXX'
    #es = Elasticsearch(es_host,)
    #es=Elasticsearch(['192.168.10.10', '192.168.10.11', '192.168.10.12'])   #连接集群
    es = Elasticsearch([es_host],
                       # 在做任何操作之前,先进行嗅探
                       # sniff_on_start=True,
                       # 节点没有响应时,进行刷新,重新连接
                       # sniff_on_connection_fail=True,
                       # # 每 60 秒刷新一次
                       # sniffer_timeout=60
                       )
    
    ###########################关于基本信息的查看############
    # #测试是否能连通
    # pprint(es.ping())
    # #查看集群的健康信息
    # pprint(es.cluster.health())
    # #查看当前集群的节点信息
    # pprint(es.cluster.client.info())
    # #查看集群的更多信息
    # pprint(es.cluster.state())
    # 使用cat查看更多信息
    # pprint(es.cat.health())
    # pprint(es.cat.master())
    # pprint(es.cat.nodes())
    # pprint(es.cat.count())

    二.关于索引的基本操作

    # 查看当前集群的所有的索引
    # pprint(es.cat.indices())
    # 创建索引
    # 创建索引的时候可以指定body参数,就是mapping的type的配置信息
    # mapping={}
    # res=es.indices.create(index='my-index',ignore=True,body=mapping)
    # pprint(res)
    # pprint(es.cat.indices())
    
    # 删除索引
    # res=es.indices.delete(index='my-index')
    # pprint(res)
    
    # 判断索引是否存在
    # res=es.indices.exists(index='my-index')
    # pprint(res)

    三.操作单条数据

    # 插入数据的时候指定的索引可以不存在,但是不建议这么做,最好先判断,不存在集创建,这样不易出问题
    
    # 添加一条数据
    # 使用index新增可以不指定id,会随机生成一个id,
    # 如果指定了id,当id存在的时候,就会对这条数据进行更新,id不存在则新建
    # 这边要注意一下,使用index更新,他会用新的字典,直接替换原来的整个字典,与update方法是不一样的
    # body = {'name': 'xiaosan', 'age': 18, 'sex': 'girl', }
    # res = es.index(index='my-index', body=body, id='OokS028BE9BB6NkUgJnI')
    # pprint(res)
    
    #使用create新增一条数据
    # 注意使用create新增数据必须指定id,create本质也是调用了index,如果id已经存在就会报错(ConflictError重复错误,所以少用)
    # body = {'name': 'xiaosan', 'age': 18, 'sex': 'girl', }
    # res=es.create(index='my-index',body=body,id=1)
    
    
    # 查询一条数据(通过id来查询)
    # res=es.get(index='my-index',id='OYkK028BE9BB6NkUOZll')
    # pprint(res)
    
    # 查询所有数据
    # body = {'query': {'match_all': {}}}
    # res = es.search(index='my-index', body=body)
    # pprint(res)
    
    # 删除数据(通过指定索引和id进行删除)
    # res=es.delete(index='my-index',id='O4kZ028BE9BB6NkUUpm4')   #删除指定id
    # pprint(res)
    # print(es.delete_by_query(index='p2', body={"query": {"match": {"age": 20}}}))  #删除符合条件
    
    
    
    # 更新数据(指定id更新数据,在es7之后要更新的数据需要用一个大字典包裹着,并且,key为doc )
    # body={'doc':{'heigh':180}}   #这个更新操作是在原来的基础上增加一个字段,而如果字段原来存在就会进行替换
    # res=es.update(index='my-index',id='OokS028BE9BB6NkUgJnI',body=body)
    
    
    #判断指定id的数据是否存在
    
    pprint(es.exists(index='person1', id='xVywInIBMTX0DMkCECea'))

    四.关于多条数据或者高级操作

    
    ######### 使用term或者terms进行精确查询
    body = {
        "query":{
            "term":{
                "name":"python"
            }
        }
    }
    ######### 查询name="python"的所有数据
    es.search(index="my-index",doc_type="test_type",body=body)
    body = {
        "query":{
            "terms":{
                "name":[
                    "python","android"
                ]
            }
        }
    }
    # 搜索出name="python"或name="android"的所有数据
    res=es.search(index="my_index",doc_type="test_type",body=body)
    print(res)
    
    
    ########### match与multi_match
    # match:匹配name包含python关键字的数据
    body = {
        "query":{
            "match":{
                "name":"python"
            }
        }
    }
    # 查询name包含python关键字的数据
    es.search(index="my_index",doc_type="test_type",body=body)
    
    body = {
        "query":{
            "multi_match":{
                "query":"深圳",
                "fields":["name","addr"]
            }
        }
    }
    # 查询name和addr包含"深圳"关键字的数据
    es.search(index="my_index",doc_type="test_type",body=body)
    
    ############ ids
    
    body = {
        "query":{
            "ids":{
                "type":"test_type",
                "values":[
                    "1","2"
                ]
            }
        }
    }
    # 搜索出id为1或2d的所有数据
    es.search(index="my_index",doc_type="test_type",body=body)
    
    ########### 复合查询bool
    #bool有3类查询关系,must(都满足),should(其中一个满足),must_not(都不满足)
    
    body = {
        "query":{
            "bool":{
                "must":[
                    {
                        "term":{
                            "name":"python"
                        }
                    },
                    {
                        "term":{
                            "age":18
                        }
                    }
                ]
            }
        }
    }
    # 获取name="python"并且age=18的所有数据
    es.search(index="my_index",doc_type="test_type",body=body)
    
    #############  切片式查询
    body = {
        "query":{
            "match_all":{}
        },
        "from":2,    # 从第二条数据开始
        "size":4    # 获取4条数据
    }
    # 从第2条数据开始,获取4条数据
    es.search(index="my_index",doc_type="test_type",body=body)
    
    ###########范围查询
    
    body = {
        "query":{
            "range":{
                "age":{
                    "gte":18,       # >=18
                    "lte":30        # <=30
                }
            }
        }
    }
    # 查询18<=age<=30的所有数据
    es.search(index="my_index",doc_type="test_type",body=body)
    
    #########前缀查询
    body = {
        "query":{
            "prefix":{
                "name":"p"
            }
        }
    }
    # 查询前缀为"赵"的所有数据
    es.search(index="my_index",doc_type="test_type",body=body)
    
    
    ######  通配符查询
    body = {
        "query":{
            "wildcard":{
                "name":"*id"
            }
        }
    }
    # 查询name以id为后缀的所有数据
    es.search(index="my_index",doc_type="test_type",body=body)
    
    
    ######## 排序
    body = {
        "query":{
            "match_all":{}
        },
        "sort":{
            "age":{                 # 根据age字段升序排序
                "order":"asc"       # asc升序,desc降序
            }
        }
    }
    
    
    ##########  filter_path
    # 只需要获取_id数据,多个条件用逗号隔开
    es.search(index="my_index",doc_type="test_type",filter_path=["hits.hits._id"])
    
    #########   获取所有数据
    es.search(index="my_index",doc_type="test_type",filter_path=["hits.hits._*"])
    
    #度量类聚合
    #获取最小值
    
    body = {
        "query":{
            "match_all":{}
        },
        "aggs":{                        # 聚合查询
            "min_age":{                 # 最小值的key
                "min":{                 # 最小
                    "field":"age"       # 查询"age"的最小值
                }
            }
        }
    }
    # 搜索所有数据,并获取age最小的值
    es.search(index="my_index",doc_type="test_type",body=body)
    
    
    
    body = {
        "query":{
            "match_all":{}
        },
        "aggs":{                        # 聚合查询
            "max_age":{                 # 最大值的key
                "max":{                 # 最大
                    "field":"age"       # 查询"age"的最大值
                }
            }
        }
    }
    
    ####### 搜索所有数据,并获取age最大的值
    es.search(index="my_index",doc_type="test_type",body=body)
    
    
    body = {
        "query":{
            "match_all":{}
        },
        "aggs":{                        # 聚合查询
            "sum_age":{                 # 和的key
                "sum":{                 #
                    "field":"age"       # 获取所有age的和
                }
            }
        }
    }
    # 搜索所有数据,并获取所有age的和
    es.search(index="my_index",doc_type="test_type",body=body)
    
    
    
    #获取平均值
    body = {
        "query":{
            "match_all":{}
        },
        "aggs":{                        # 聚合查询
            "avg_age":{                 # 平均值的key
                "sum":{                 # 平均值
                    "field":"age"       # 获取所有age的平均值
                }
            }
        }
    }
    # 搜索所有数据,获取所有age的平均值
    es.search(index="my_index",doc_type="test_type",body=body)

    五.对返回的字段进行过滤

       filter_path参数用于过滤减少es返回信息,可以指定返回相关的内容,还支持一些通配符的操作*

    # 主要是对_source同一级的字段进行过滤
    print(es.search(index="p1", body=body, filter_path=["hits.hits"]))
    print(es.search(index="p1", body=body, filter_path=["hits.hits._source"]))
    print(es.search(index="p1", body=body, filter_path=["hits.hits._source", "hits.total"]))
    print(es.search(index="p1", body=body, filter_path=["hits.*"]))
    print(es.search(index="p1", body=body, filter_path=["hits.hits._*"]))

    六.获取数据量

    #########  count
    #执行查询并获取该查询的匹配数
    
    ########  获取数据量
    es.count(index="my_index",doc_type="test_type")
    
    
    pprint(es.count(index='person'))
    pprint(es.count(index='person')['count'])

       结果:

    {'_shards': {'failed': 0, 'skipped': 0, 'successful': 1, 'total': 1},
     'count': 1}
    1
  • 相关阅读:
    python---RabbitMQ(1)简单队列使用,消息依次分发(一对一),消息持久化处理
    python---ORM之SQLAlchemy(4)relationship多对多练习
    ShowcaseView-master
    HT518V311
    上方显示进度的进度条
    ArrowDrawable
    一个仿 github for windows 及 windows 8 的进度条
    高仿语音发送动画,按住闪烁,滑动跟随,删除翻转丢入垃圾桶,比较全的一个动画实例
    Ledongli
    RotatingDoughnut
  • 原文地址:https://www.cnblogs.com/tjp40922/p/12231752.html
Copyright © 2011-2022 走看看