python 操作elasticsearch 基本用法

创建es索引库,相当于创建一个表

     from elasticsearch import Elasticsearch
     from elasticsearch.helpers import bulk
     es = Elasticsearch(hosts='localhost:9200')
     #创建索引表
     es.indices.create(index='my', ignore=400)

插入一条数据到es的索引库中

  data = {
   "name": "小明", "age": "8", "gender": "男"}
  res = es.index(index='my', doc_type='doc', body=data)

批量插入数据到索引库中

    from elasticsearch.helpers import bulk
    data_lis = [{
   "name": "小红", "age": "8", "gender": "女"}, {
   "name": "小王", "age": "8",    "gender": "男"}]
    # 批量插入es创建的索引表
    res2 = bulk(es, data_lis, index='my' )

查询所有的数据

    data = es.search(index='my')
    #查询所有的第二种方法
    body = {
   
            'query':{
   
            'match_all':{
   }
             }
        }
    data = es.search(index='my', body=body)

term: 根据某个字段的值进行查询数据

    # es 官方文档: term 和 terms 是 包含(contains) 操作,而非 等值(equals) (判断)
    body2 =  {
   
                 "query":{
   
                   "term":{
   
                      "age":8 }
                          }
                        }
    data_list = es.search(index='my', body=body2)

terms: 根据某个字段的多个值进行查询数据

    body3 = {
   
               "query":{
   
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
利用Python操作Elasticsearch可以使用elasticsearchelasticsearch-dsl这两个库,也可以使用更为简单的es-pandas库。其中,elasticsearch库提供了与Elasticsearch交互的低级接口,而elasticsearch-dsl库则提供了更高级别的查询构建器和对象映射器。es-pandas库则提供了一种将Elasticsearch数据转换为pandas DataFrame的简单方法。 以下是一个使用elasticsearch库进行查询的例子: ```python from elasticsearch import Elasticsearch # 连接到Elasticsearch es = Elasticsearch() # 查询所有文档 res = es.search(index="my_index", body={"query": {"match_all": {}}}) # 输出结果 for hit in res['hits']['hits']: print(hit['_source']) ``` 以下是一个使用elasticsearch-dsl库进行查询的例子: ```python from elasticsearch import Elasticsearch from elasticsearch_dsl import Search # 连接到Elasticsearch es = Elasticsearch() # 创建查询对象 s = Search(using=es, index="my_index").query("match", title="python") # 执行查询并输出结果 response = s.execute() for hit in response: print(hit.title) ``` 以下是一个使用es-pandas库将Elasticsearch数据转换为pandas DataFrame的例子: ```python from es_pandas import es_pandas # 将Elasticsearch数据转换为pandas DataFrame df = es_pandas.DataFrame({ "host": {"field": "host.keyword"}, "response": {"field": "response_time_ms"}, "timestamp": {"field": "@timestamp", "dtype": "datetime64[ns]"} }, es_url="http://localhost:9200", es_index_pattern="my_index-*") # 输出DataFrame print(df.head()) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值