使用Python操作Elasticsearch数据索引的教程

这篇文章主要介绍了使用Python操作Elasticsearch数据索引的教程,Elasticsearch处理数据索引非常高效,要的朋友可以参考下

Elasticsearch是一个分布式、Restful的搜索及分析服务器,Apache Solr一样,它也是基于Lucence的索引服务器,但我认为Elasticsearch对比Solr的优点在于:

  • 轻量级:安装启动方便,下载文件之后一条命令就可以启动;
  • Schema free:可以向服务器提交任意结构的JSON对象,Solr中使用schema.xml指定了索引结构;
  • 多索引文件支持:使用不同的index参数就能创建另一个索引文件,Solr中需要另行配置;
  • 分布式:Solr Cloud的配置比较复杂。

环境搭建

启动Elasticsearch,访问端口在9200,通过浏览器可以查看到返回的JSON数据,Elasticsearch提交和返回的数据格式都是JSON.

1
>> bin/elasticsearch -f

安装官方提供的Python API,在OS X上安装后出现一些Python运行错误,是因为setuptools版本太旧引起的,删除重装后恢复正常。

1
>> pip install elasticsearch

索引操作

对于单条索引,可以调用create或index方法。

1
2
3
4
5
from datetime import datetime
from elasticsearch import Elasticsearch
es = Elasticsearch() #create a localhost server connection, or Elasticsearch("ip")
es.create(index="test-index", doc_type="test-type", id=1,
  body={"any":"data", "timestamp": datetime.now()})

Elasticsearch批量索引的命令是bulk,目前Python API的文档示例较少,花了不少时间阅读源代码才弄清楚批量索引的提交格式。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
from datetime import datetime
from elasticsearch import Elasticsearch
from elasticsearch import helpers
es = Elasticsearch("10.18.13.3")
j = 0
count = int(df[0].count())
actions = []
while (j < count):
   action = {
        "_index": "tickets-index",
        "_type": "tickets",
        "_id": j + 1,
        "_source": {
              "crawaldate":df[0][j],
              "flight":df[1][j],
              "price":float(df[2][j]),
              "discount":float(df[3][j]),
              "date":df[4][j],
              "takeoff":df[5][j],
              "land":df[6][j],
              "source":df[7][j],
              "timestamp": datetime.now()}
        }
  actions.append(action)
  j += 1
 
  if (len(actions) == 500000):
    helpers.bulk(es, actions)
    del actions[0:len(actions)]
 
if (len(actions) > 0):
  helpers.bulk(es, actions)
  del actions[0:len(actions)]

在这里发现Python API序列化JSON时对数据类型支撑比较有限,原始数据使用的NumPy.Int32必须转换为int才能索引。此外,现在的bulk操作默认是每次提交500条数据,我修改为5000甚至50000进行测试,会有索引不成功的情况。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#helpers.py source code
def streaming_bulk(client, actions, chunk_size=500, raise_on_error=False,
    expand_action_callback=expand_action, **kwargs):
  actions = map(expand_action_callback, actions)
 
  # if raise on error is set, we need to collect errors per chunk before raising them
  errors = []
 
  while True:
    chunk = islice(actions, chunk_size)
    bulk_actions = []
    for action, data in chunk:
      bulk_actions.append(action)
      if data is not None:
        bulk_actions.append(data)
 
    if not bulk_actions:
      return
 
def bulk(client, actions, stats_only=False, **kwargs):
  success, failed = 0, 0
 
  # list of errors to be collected is not stats_only
  errors = []
 
  for ok, item in streaming_bulk(client, actions, **kwargs):
    # go through request-reponse pairs and detect failures
    if not ok:
      if not stats_only:
        errors.append(item)
      failed += 1
    else:
      success += 1
 
  return success, failed if stats_only else errors

对于索引的批量删除和更新操作,对应的文档格式如下,更新文档中的doc节点是必须的。

1
2
3
4
5
6
7
8
9
10
11
12
13
{
  '_op_type': 'delete',
  '_index': 'index-name',
  '_type': 'document',
  '_id': 42,
}
{
  '_op_type': 'update',
  '_index': 'index-name',
  '_type': 'document',
  '_id': 42,
  'doc': {'question': 'The life, universe and everything.'}
}

常见错误

  • SerializationError:JSON数据序列化出错,通常是因为不支持某个节点值的数据类型
  • RequestError:提交数据格式不正确
  • ConflictError:索引ID冲突
  • TransportError:连接无法建立

性能

上面是使用MongoDB和Elasticsearch存储相同数据的对比,虽然服务器和操作方式都不完全相同,但可以看出数据库对批量写入还是比索引服务器更具备优势。

Elasticsearch的索引文件是自动分块,达到千万级数据对写入速度也没有影响。但在达到磁盘空间上限时,Elasticsearch出现了文件合并错误,并且大量丢失数据(共丢了100多万条),停止客户端写入后,服务器也无法自动恢复,必须手动停止。在生产环境中这点比较致命,尤其是使用非Java客户端,似乎无法在客户端获取到服务端的Java异常,这使得程序员必须很小心地处理服务端的返回信息。

es批量索引的更多相关文章

  1. ES批量索引写入时的ID自动生成算法

    对bulk request的处理流程: 1.遍历所有的request,对其做一些加工,主要包括:获取routing(如果mapping里有的话).指定的timestamp(如果没有带timestamp ...

  2. es修改索引副本个数

    es修改索引副本个数 PUT index01/_settings { "number_of_replicas": 2 }

  3. ES-PHP向ES批量添加文档报No alive nodes found in your cluster

    ES-PHP向ES批量添加文档报No alive nodes found in your cluster 2016年12月14日 12:31:40 阅读数:2668 参考文章phpcurl 请求Chu ...

  4. 批量索引以提高索引速度 -d --data-binary

    index create update 第1.2行分别为:信息行.数据行,在索引中增加或更换文档delete 移除文档,只包含信息行 Bulk API | Elasticsearch Referenc ...

  5. es创建索引的格式,并初始化数据

    es创建索引的格式,并初始化数据 学习了:https://www.imooc.com/video/15759 1, 创建格式 POST 127.0.0.1:9200/book/novel/_mappi ...

  6. ES读写索引内幕分析

    一.简介 ES中的索引都进行分片,每个分片都会保存多个副本.这些副本称为复制组,在添加或删除索引时必须同步副本.如果不这样,从不同的副本中读取的索引可能截然不同.保持分片副本同步并从中提供读取的过程被 ...

  7. es批量导入进一对多的数据

    es批量导入进一对多的数据 我有一个产品表 一个产品对应多个属性名 一个属性名对应多个属性值 一个产品还对应一个分类名称    控制层 @ApiOperation(value = "导入所有 ...

  8. ES 服务器 索引、类型仓库基类 BaseESStorage

    /******************************************************* * * 作者:朱皖苏 * 创建日期:20180508 * 说明:此文件只包含一个类,具 ...

  9. 在ES批量插入数据超时时自动重试

    当我们使用ES批量插入数据的时候,一般会这样写代码: from elasticsearch import Elasticsearch,helpers es =Elasticsearch(hosts=[ ...

随机推荐

  1. Cisco基础(一):Vlan的划分、配置trunk中继链路、以太通道配置、DHCP服务配置

    一.Vlan的划分 目标: VLAN(虚拟局域网)是对连接到的第二层交换机端口的网络用户的逻辑分段,不受网络用户的物理位置限制而根据用户需求进行网络分段.一个VLAN可以在 一个交换机或者跨交换机实现 ...

  2. paper 144:人生苦短,快用Python

    1.Python 语言特点 Python是一种面向对象.直译式计算机程序设计语言,这种语言的语法简捷而清晰,具有丰富和强大的类库,基本上能胜任你平时需要的编程工作. Python的优点: (1)编写的 ...

  3. Xcode5 统计单元测试覆盖率(仅限XCTest)

    概要 通过本篇文章,你将学会如何在Xcode5下使用统计XCTest测试代码的覆盖率,以及如何快速得到测试覆盖率的图形化报表. 为什么要特别说明Xcode5下的代码覆盖率统计,原因是,以前的方法在新环 ...

  4. Mysql安装和简单设置

    MySQL安装文件分为两种,一种是msi格式的,一种是zip格式的.如果是msi格式的可以直接点击安装,按照它给出的安装提示进行安装(相信大家的英文可以看懂英文提示),一般MySQL将会安装在C:\P ...

  5. Nginx网络架构实战学习笔记(一):Nginx简介、安装、信号控制、nginx虚拟主机配置、日志管理、location 语法、Rewrite语法详解

    文章目录 nginx简介 nginx安装 nginx信号控制 nginx虚拟主机配置 日志管理 location 语法 精准匹配的一般匹配 正则匹配 总结 Rewrite语法详解 nginx简介 Ng ...

  6. eclipse中选取一列快捷键

    eclipse中选取一列 比如选中下面的1 4 1   2   3 4   5   6 快捷键 alt+shift+拖动鼠标

  7. switch gnome-terminal tabs

    Ctrl+Page Down (forward) and Ctrl+Page Up (backward). http://unix.stackexchange.com/a/67963

  8. pandas 使用出现的问题汇总

    问题1:<bound method NDFrame.head of 刚开始还以为是自己的数据集有问题,怎么显示不对呢! 解决: 仔细观察,是自己给的输出有问题,data.head什么鬼??? 正 ...

  9. Java web后台插入数据库中文乱码问题解决

    前言:项目想要避免乱码情况的出现,要保持服务器.数据库.项目.以及前端编码一致.一.项目以及前端编码,设置. myeclipse--->右键项目--->Properties--->R ...

  10. mysql 针对table的查看命令行

    1  desc t_help; 2 show create table t_help; 3  show table status like 't_help';