elasticsearch之增删改查

1 安装

pip install elasticsearch

官方文档是:Python Elasticsearch Client — Elasticsearch 7.15.2 documentation

中文社区:Elastic中文社区

权威指南:https://es.xiaoleilu.com/index.html

2 连接

obj = ElasticSearchClass("0.0.0.0", "9200", "", "")

from elasticsearch import Elasticsearch

class ElasticSearchClass(object):

    def __init__(self, host, port, user, passwrod):
        self.host = host
        self.port = port
        self.user = user
        self.password = passwrod
        self.connect()

    def connect(self):
        """客户端的连接"""
        self.es = Elasticsearch(hosts=[{'host': self.host, 'port': self.port}],
                                http_auth=(self.user, self.password ))

    def create():
         result = es.indices.create(index='news', ignore=400)  #  创建 Index
         return result 
 

    def insert(self, index, type, body, id=None):
        '''
        插入一条body给指定的index、指定的type下;
        可指定Id,若不指定,ES会自动生成
        :param index: 待插入的index值
        :param type: 待插入的type值, # es7后取消
        :param body: 待插入的数据  # dict型
        :param id: 自定义Id值
        :return:
        '''
        self.es.create(index=index, doc_type=type, body=body, id=id) # 需指定
        return self.es.index(index=index, doc_type=type, body=body, id=id)

    def count(self, indexname):
        """
        :return: 统计index总数
        """
        return self.conn.count(index=indexname)

    def delete(self, indexname, doc_type, id):
        """
        :param indexname:
        :param doc_type:
        :param id:
        :return: 删除index中具体的一条
        """
        self.es.delete(index=indexname, doc_type=doc_type, id=id)

    def delete_by_query(self, index, unique_id=False):
        if unique_id:
            self.es.delete(index=index, id=unique_id)
        else:
            self.es.delete_by_query(index, body= {'query': {'match_all': {}}})
         
    def delete_index(self, index):
        # 删除所有索引
        if not index:
            for index in es.indices.get("*"):
                es.indices.delete(index)
        else:
            es.indices.delete(index)

    def get(self, doc_type, indexname, id):
        # index中具体的一条
        return self.es.get(index=indexname,doc_type=doc_type, id=id)
    

    def update(self, doc_type, indexname,  body=data, id):
        # 更新其中具体的一条
        return self.es.update(index=indexname,doc_type=doc_type,  body=data, id=id)

    def searchindex(self, index):
        """
        查找所有index数据
        """
        try:
            return self.es.search(index=index)
        except Exception as err:
            print(err)

    def searchDoc(self, index=None, type=None, body=None):
        '''
        查找index下所有符合条件的数据
        :param index:
        :param type:
        :param body: 筛选语句,符合DSL语法格式
        :return:
        '''
        return self.es.search(index=index, doc_type=type, body=body)

    def search(self,index,type,body,size=10,scroll='10s'):
        """
        根据index,type查找数据,
        其中size默认为十条数据,可以修改为其他数字,但是不能大于10000
        """
        return self.es.search(index=index,  
                              doc_type=type,body=body,size=size,scroll=scroll)

    def scroll(self, scroll_id, scroll):
        """
        根据上一个查询方法,查询出来剩下所有相关数据
        """
        return self.es.scroll(scroll_id=scroll_id, scroll=scroll)

    def proportion_not_null(self, index, field=None):
        """非空统计"""
        a = self.count(index)['count']
        b = self.count(index, {'query': {'bool': {'must': {'exists': {'field': 
                                                                     field}}}}})['count']
        print(field, a, b, b / a)

    def aggs_terms(self, index, field, size=15):
        """单字段统计"""
        return self.search({
            'aggs': {
                'CUSTOM NAME': {
                    'terms': {
                        'field': field,
                        'size': size,  # 解决aggs显示不全
                    }
                }
            }
        }, index)['aggregations']['CUSTOM NAME']['buckets']

3 操作

from elasticsearch import Elasticsearch
# 1.elasticsearch的连接
obj = ElasticSearchClass("0.0.0.0", "9200", "", "") 

# 2.数据的的插入
obj.insertDocument(index=”question”,type='text,id=9,
     body= {"any":body,"timestamp":datetime.now()})

# 其中index和type是固定传入,id可以自己传入也可以系统生成,其中body数据为自己组合的数据

# 3.数据的删除
dd = obj.delete(index='question', type='text', id=7310)

# 数据删除时候是根据id进行删除,删除数据时候,
# index,type需要和之前传入时候的index,type保持一致
# 4.  数据的搜索

# 4.1、通过index搜索数据  其中,搜索之后数据显示默认为十条数据
res = obj.search(indexname=index)

# 4.2、通过body搜索数据

# 4.2.1、全部匹配:

# 查询所有数据
body = {
    "query":{
        "match_all":{}
    }
}
response = obj.search(index="question",type="text",body=body)
# 返回的数据默认显示为十条数据,其中hits[“total”]为查询数量总数


# 其中Match_all 默认匹配所有的数据
# 4.2.2、广泛匹配某个字段
body = {
    "query" : {
        "match" : {
            "data.content" : "马上马上"
        }
    }
}
# Match默认匹配某个字段
response = obj.search(index="question",type="text",body=body)


# 4.2.3、匹配多个字段
body = {
  "query": {
    "bool": {
      "should": [
        { "match": { "data.content":  "一根铁丝" }},
        { "match": { "data.question_content": "一根铁丝"  }},
        { "match": { "data.ask_content.content": '一根铁丝' }}
      ],
    }
  }
}
# Should或匹配可以匹配某个字段也可以匹配所有字段,其中至少有一个语句要匹配,与 OR 等价
response = obj.search(index="question",type="text",body=body,scroll='5s') 

# 4.2.4、匹配所有字段
body = {
  "query": {
    "bool": {
      "must": [
        { "match": { "data.content":  "李阿姨" }},
        { "match": { "data.question_content": "李阿姨"   }},
        { "match": { "data.ask_content.content": '李阿姨' }}
      ],
    }
  }
}
Must必须匹配所有需要查询的字段, 与 and 等价
response = obj.search(index="question",type="text",body=body,scroll='5s')


# 4.2.5、短语匹配查询:
# 精确匹配一系列单词或者短语
body = {
    "query" : {
        "match_phrase" : {
            "data.content" : "一根铁丝"
        }
    }
}
response = obj.search(index="question",type="text",body=body,scroll='5s')



# 4.2.6、高亮搜索:
# Elasticsearch 中检索出高亮片段。highlight 参数:
Body = {
    "query" : {
        "match_phrase" : {
            "about" : "rock climbing"
        }
    },
    "highlight": {
        "fields" : {
            "about" : {}
        }
    }
}
# 当执行该查询时,返回结果与之前一样,与此同时结果中还多了一个叫做 highlight 的部分。
# 这个部分包含了about 属性匹配的文本片段,并以 HTML 标签 <em></em> 封装:
{
   ...
   "hits": {
      "total":      1,
      "max_score":  0.23013961,
      "hits": [
         {
            ...
            "_score":         0.23013961,
            "_source": {
               "data.content":       "李阿姨"
                       },
            "highlight": {
               "about": [
                  "张阿姨和<em>李阿姨</em>" 
               ]
            }
         }
      ]
   }
}


#5 分页+排序
{
    'from': 20,
    'size': 10,
    'query': {'match': {'full_name': '老婆'}},
    'sort': {'_id': {'order': 'asc'}}
}

4 curl命令交互

cURL是一个利用URL语法在命令行下工作的文件传输工具(CommandLine Uniform Resource Locator)

curl -X<VERB> '<PROTOCOL>://<HOST>:<PORT>/<PATH>?<QUERY_STRING>' -d '<BODY>'

curl -XGET 'http://localhost:9200/_count?pretty' -d '
{"query": {"match_all": {}}}
'

 
 

参考:

Python基于Elasticsearch实现搜索引擎

Elasticsearch 的站内搜索引擎实战

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
要在Python中进行Elasticsearch增删改查操作,你可以使用Elasticsearch的官方库elasticsearch-py来实现。下面是一个简单的例子来演示如何进行增删改查操作: 引用: 首先,你需要导入Elasticsearch库并连接到Elasticsearch服务器: ```python from elasticsearch import Elasticsearch # 连接到Elasticsearch服务器 es = Elasticsearch([ES_IP], http_auth=('elastic', '123456'), port=ES_PORT) ``` 引用: 查询数据: - 查询所有数据: ```python body = { "size": 111, # 最大显示数量,es默认展示10条 "query": { "match_all": {} } } res = es.search(index='my-index', body=body, request_timeout=30) ``` - 查询具体某个字段: ```python body = { "size": 10000, # 最大显示数量 "query": { "match": { "text": { "query": search_key, "analyzer": "ik_smart", # 用来指定搜索的词语按那种拆词粒度拆词 "operator": "or", # 按拆分后的词查询时,词与词之间是 and 还是 or 的关系 "minimum_should_match": "75%" # 该参数用来控制应该匹配的分词的最少数量,至少匹配几个词才召回查询的结果 } } } } res = es.search(index='my-index', body=body, request_timeout=30) ``` 引用: 获取拆分后的词: 你可以使用Elasticsearch的analyze API来获取拆分后的词,例如: ```python body = { "text": "惠普 p2015dn", "analyzer": "ik_max_word" } res = es.indices.analyze(index='my-index', body=body) key_list = [dic['token'] for dic in res['tokens']] print(key_list) # ['惠普', 'p2015dn', 'p', '2015', 'dn'] ``` 以上是关于在Python中使用Elasticsearch进行增删改查的基本操作。你可以根据具体的需求使用不同的查询方式,并根据返回的结果进行相应的处理。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [python 使用 Elasticsearch 增删查改](https://blog.csdn.net/Waller_/article/details/109810964)[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_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

**星光*

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值