如何使用python检查API中的数据是否在elasticsearch索引中,如果不是,请插入i

2024-04-20 14:44:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从开放的天气图API中检索一些数据,并用Python将它们插入到一个Elasticsearch索引中。然后我会拿一些新的,看看它们是否已经在索引中了。如果没有,我会把它们加到索引中。如果他们已经在其中,他们应该被忽略。在

import datetime
from pprint import pprint
import requests
import urllib
import json
import request
from elasticsearch import Elasticsearch
from elasticsearch import helpers
import time

es = Elasticsearch([{'host': 'localhost', 'port': 9200}])
r = requests.get('http://api.openweathermap.org/data/2.5/weather?q=London&appid=###').json()
pprint(r)

res = es.search(index="weathermap", body={"query": {"match_all": {}}})

for m in res:
   if m not in res:
      es.index(index='weathermap', doc_type='doc')

Tags: infromimportjsonindexdocesres
2条回答

您可以使用以下代码

import datetime
from pprint import pprint
import requests
import urllib
import json
import request
from elasticsearch import Elasticsearch
from elasticsearch import helpers
import time

es = Elasticsearch([{'host': 'localhost', 'port': 9200}])
r = requests.get('http://api.openweathermap.org/data/2.5/weather?q=London&appid=###').json()
pprint(r)

res = es.search(index="weathermap", body={"query": {"match_all": {}}})

for m in res['hits']['hits']:
   if search_value not in res:
      es.index(index='weathermap', doc_type='doc',whole_doc_body)

与其检查它是否存在,如果不存在就添加它,您可以让Elastic为您完成所有这些。与使用es.index(...)不同,您可以调用es.create(...),如{a1}文档中所指定的那样。在

Adds a typed JSON document in a specific index, making it searchable. Behind the scenes this method calls index(…, op_type=’create’)

Elastic documentation

The index operation also accepts an op_type that can be used to force a create operation, allowing for "put-if-absent" behavior. When create is used, the index operation will fail if a document by that id already exists in the index.

所以如果不插入,它会抛出一个错误,所以一定要处理它。在

相关问题 更多 >