使用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. php-fpm.conf详细解析篇

    一:php-fpm.conf详细解析篇: pm = static (静态模式)时只需修改 max_children数值 pm = dynamic (动态模式)时只需修改其它三个数值 pm.max_ch ...

  2. java 多级图的最短路径

    求最短路径众所周知有Dijistra算法.Bellman-ford等,除了这些算法,用动态规划也可以求出最短路径,时间复杂度为O(n^2), 跟没有优化的Dijistra算法一样(优化后的Dijist ...

  3. how to convert from hex to disasm

    cat ascii.hex | ascii2binary -b h -t us > ascii.bin x86dis -e 0 -s att -f ascii.bin echo "d8 ...

  4. uoj175 【Goodbye Yiwei】新年的网警

    题目 胡乱分析 不妨定谣言的源头得到谣言的时刻为\(1\),那么其他人听到谣言的时间就是源头到这个点的最短路 假设\(i\)是谣言的源头,那么如果存在一个点\(j\)满足\(\forall k\in[ ...

  5. 十次艳遇单例设计模式(Singleton Pattern)

    1.引言 单例设计模式(Singleton Pattern)是最简单且常见的设计模式之一,在它的核心结构中只包含一个被称为单例的特殊类.通过单例模式可以保证系统中一个类只有一个实例而且该实例易于外界访 ...

  6. Spring Boot实现通用的接口参数校验

    Spring Boot实现通用的接口参数校验 Harries Blog™ 2018-05-10 2418 阅读 http ACE Spring App API https AOP apache IDE ...

  7. elementUI 的el-pagination 分页功能

    <div class="block1"> <el-pagination @size-change="handleSizeChange" @cu ...

  8. Node.js中的fs文件系统

    fs.stat 检测是文件还是目录 fs.mkdir 创建目录 fs.writeFile 创建写入文件 fs.appendFile 追加文件 fs.readFile 读取文件 fs.readdir 读 ...

  9. 微信小程序のwxss

    一.wxss简介 wxss是微信小程序的样式文件,同h5框架的css类似,它具有以下特性: 二.外联样式导入 我们可以通过@import引入外部文件的样式 小程序样式是从上到下,从左到右执行的,如果样 ...

  10. 每天一个Linux常用命令 命令

    指令名称 : chmod 使用权限 : 所有使用者 使用方式 :chmod 777 /root 第一个7指文件所属用户,第二个7指文件所属用户的用户组,第三个7指其他用户 说明 : Linux/Uni ...