简体   繁体   中英

How to send a dictionary in bulk to elasticsearch?

I have an index in below format:

"the debt": {"node": ["04j0t75", "0crxlv5"], "levenshtein": [100, 100]},
"nobuo": {"node": ["0ftqr"], "levenshtein": [56]},
"uematsu": {"node": ["0ftqr"], "levenshtein": [70]}

I want to send this index to elasticsearch with python client. I use below code snippet

from elasticsearch import Elasticsearch
from elasticsearch.helpers import bulk

es = Elasticsearch(hosts=[{"local": '9200'}])
test_index = json.loads(json.dumps(inverse_index))
actions = [
    {
    '_index': 'test_index',
    '_type': 'application/json',
    '_id': i,
    '_source': json.loads('"{{{0}: {1}}}"'.format(k, v)),
   }
for i, (k, v) in enumerate(test_index.items(), 1)
 ] 
  bulk(es, actions)

I am getting below error:

Unexpected character ('u' (code 117)): was expecting double-quote to start field name\n at [Source

I think it wants me to wrap the keys with double quotes but I couldn't manage to do it somehow.

Could you help me?

Thanks in advance!

Not sure why you're formatting the key-value string and then json-loading it within the actions loop...

Instead of

'_source': json.loads('"{{{0}: {1}}}"'.format(k, v))

do

'_source': {k: v}

So:

actions = [
    {
        '_index': 'test_index',
        '_type': 'application/json',
        '_id': i,
        '_source': {k: v},
    }
    for i, (k, v) in enumerate(test_index.items(), 1)
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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