Pythonの基礎:Pythonは、インデックス付きデータ操作Elasticsearchをチュートリアル

この記事では、Pythonのチュートリアル操作するElasticsearchデータインデックスを使用することを記載し、Elasticsearchを処理するインデックスデータは非常に効率的で、友人を参照することができ
、それはまたLucenceに基づいているとして、Elasticsearchは、分散、RESTfulな検索や分析サーバーは、Apache Solrのですインデックスサーバーが、私はSolrの中Elasticsearch比較優位の嘘を考えます:

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

ビルドへの環境

あなたはJSONデータを表示することができますスタートElasticsearch、9200でのアクセスポートは、ブラウザによって返され、Elasticsearchの提出とデータ形式のリターンはJSONです。

>> bin/elasticsearch -f

公式が提供するAPIのPythonをインストールsetuptoolsのバージョンがリロードを削除した後に正常に戻ることによる古すぎるので、Pythonのランタイムエラーのいくつかは、OS Xにインストールした後に発生します。

>> pip install elasticsearch

インデックスの操作

単一のインデックスのために、あなたは電話またはインデックスメソッドを作成することができます。

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一括受注指数は現在、PythonのAPIドキュメントの例以下、単にバッチ形式のインデックスを提出把握するためにソースコードを読むために多くの時間を費やし、バルクです。

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シリアライズのサポート、より限定された種類、int型のインデックスに変換するために使用NumPy.Int32生データを見つけました。また、今で一括操作のデフォルトは提出データごとに500ですが、私は状況の意志指数が失敗し、テスト5000あるいは50,000を修正しました。

#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

バルク削除および更新操作の指標のために、対応する文書のフォーマットは、以下のように、ドキュメント・ノードが文書が必要である更新です。

{
  '_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例外、でサーバに取得するように見えることができない、より致命的です。
誰もが、リソースの収集を学ぶ非常に広いのpythonをお勧めし、ために私は、あなたへの書き込み入力する]をクリックし、共有の経験に学ぶ前に、上級プログラマがあり、研究ノート、ビジネス経験の可能性がある、と皆のために注意深くのpythonゼロを整理します細部のメッセージを残すことを学んで、実際のプロジェクトデータ、最新の技術上のあなたに、毎日のpython、見通しの根拠

公開された38元の記事 ウォン称賛10 ビュー50000 +

おすすめ

転載: blog.csdn.net/haoxun11/article/details/105036608