简体   繁体   English

如何使用python在弹性搜索索引中存储键值对

[英]How to store key-value pairs in an elasticsearch index using python

I want to store the contents of the dict into an elasticsearch index as follows . 我想将dict的内容存储到elasticsearch索引中,如下所示。 Is it correct or is there a better way to do it . 这是正确的还是有更好的方法来做到这一点。

    def process(self, inputDict):
       for k, v in inputDict.items():
        # for each key-value pair, store it as a field and string inside the specified index of elastic search.
          key1=k
          value1=v
          doc={
            "key1" : "value" ,
            }
          self.es.index(index='test-index2',doc_type='exdoc', id=1, body=doc)
    pass;

First of all: Did you try your code? 首先:你尝试过代码吗? I tried it and it ran without errors. 我试了一下,它运行没有错误。 That means that there must be some documents in the index test-index2 . 这意味着索引test-index2必定有一些文档。 Running it inside idle I got the the following output: 空闲状态下运行我得到以下输出:

{'_index': 'test-index2', '_type': 'exdoc', '_id': '1', '_version': 1, '_shards': {'failed': 0, 'total': 2, 'successful': 1}, 'created': True}
{'_index': 'test-index2', '_type': 'exdoc', '_id': '1', '_version': 2, '_shards': {'failed': 0, 'total': 2, 'successful': 1}, 'created': False}
{'_index': 'test-index2', '_type': 'exdoc', '_id': '1', '_version': 3, '_shards': {'failed': 0, 'total': 2, 'successful': 1}, 'created': False}

See that _version field in there? 看那里的_version字段? That looks suspicious. 这看起来很可疑。 Querying elasticsearch from sense with 意义上查询弹性搜索

GET test-index2/exdoc/_search
{
  "query": {
    "match_all": {}
  }
}

will give you the following output: 会给你以下输出:

{
  "took": 3,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 1,
    "max_score": 1,
    "hits": [
      {
        "_index": "test-index2",
        "_type": "exdoc",
        "_id": "1",
        "_score": 1,
        "_source": {
          "key1": "value"
        }
      }
    ]
  }
}

There is only one document there: {"key1": "value"} . 那里只有一个文件: {"key1": "value"} So you are always sending the same document - ignoring the keys and values from inputDict - for the same id ( id=1 ) to elasticsearch. 所以你总是发送相同的文档 - 忽略inputDict的键和值 - 对于相同的id( id=1 )到elasticsearch。 I think you wanted something like this instead: 我觉得你想要这样的东西:

def process(self, inputDict):
       i = 1 
       for k, v in inputDict.items():
        # for each key-value pair, store it as a field and string inside the specified index of elastic search.
          doc={
            k: v
            }
          self.es.index(index='test-index2',doc_type='exdoc', id=i, body=doc)
          i += 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM