zoukankan      html  css  js  c++  java
  • Elasticsearch Python API-Python Client

    Elasticsearch -Python Client ,Python API

    API Documentation

    所有API调用都尽可能接近地映射原始REST api,包括调用的必需参数和可选参数之间的区别。这意味着代码区分了位置参数和关键字参数。但是,我们建议在所有调用中都使用关键字参数,以确保一致性和安全性。

    初次使用

    安装 elasticsearch

    pip install elasticsearch
    

    连接 elasticsearch

    from elasticsearch import Elasticsearch
    es = Elasticsearch(hosts='127.0.0.1:9200') 	# hosts为 elasticsearch 监听地址,默认端口9200,本机连接请使用localhost
    

    创建 index

    from elasticsearch import Elasticsearch
    es = Elasticsearch()
    doc = {
        'title': '美方要求中方关闭休斯顿领馆',
        'us_reason': '间谍活动、窃取资料',
        'cn_response': '强烈谴责、坚决反对'
    }
    res = es.index(index='test_news', id=1, body=doc)
    print(res)
    

    image-20200723210713705

    get 查询

    from elasticsearch import Elasticsearch
    es = Elasticsearch()
    res = es.get(index='test_news', id=1)
    print(res)
    print(res['_source'])
    

    image-20200723210831282

    search 查询

    from elasticsearch import Elasticsearch
    es = Elasticsearch(hosts='127.0.0.1:9200')
    
    doc = {
        'query':
            {
                'match_all':{}
            }
    }
    res = es.search(index='test_news', body=doc)
    print(res)
    

    image-20200723212845551

    Ignore 忽略

    如果elasticsearch返回2XX响应,则认为API调用成功(并将返回响应)。否则,返回Status_code

    ,有时为了不让程序引发异常,可以使用Ignore忽略指定的Status_Code,来让程序正常运行。


    查询一个不存在的id 返回StatusCode404

    from elasticsearch import Elasticsearch
    es = Elasticsearch()
    res = es.get(index='test_news', id=5)
    print(res)
    print(res['_source'])
    

    image-20200724161047455

    使用Ignore 忽略404 错误

    from elasticsearch import Elasticsearch
    es = Elasticsearch()
    res = es.get(index='test_news', id=5, ignore=404)
    print(res)
    

    image-20200724161306436

    程序不再引发异常

    filter_path 响应过滤

    例如,仅返回_id和_source.cn_response :

    from elasticsearch import Elasticsearch
    es = Elasticsearch()
    res = es.get(index='test_news', id=1, filter_path=['_id', '_source.cn_response'])
    print(res)
    

    image-20200724162012764

    ...官网Api :url

    https://elasticsearch-py.readthedocs.io/en/master/api.html

  • 相关阅读:
    python线程池ThreadPoolExecutor用法
    redis学习笔记
    selenium + chrome 被检测,反反爬小记
    RabbitMQ单机快速安装使用
    NFS配置使用
    通过Rsync实现文件远程备份
    MySQL笔记-高可用方案
    Redis主从同步、哨兵模式、集群模式配置
    Redis维护笔记
    MongoDB笔记03——分片集群
  • 原文地址:https://www.cnblogs.com/pandaa/p/13372623.html
Copyright © 2011-2022 走看看