我终于找到了使用opensearch-py的方法,如下。
首先建立客户端,
# First fetch credentials from environment defaults
# If you can get this far you probably know how to tailor them
# For your particular situation. Otherwise SO is a safe bet :)
import boto3
credentials = boto3.Session().get_credentials()
region='eu-west-2' # for example
auth = AWSV4SignerAuth(credentials, region)
# Now set up the AWS 'Signer'
from opensearchpy import OpenSearch, RequestsHttpConnection, AWSV4SignerAuth
auth = AWSV4SignerAuth(credentials, region)
# And finally the OpenSearch client
host=f"...{region}.es.amazonaws.com" # fill in your hostname (minus the https://) here
client = OpenSearch(
hosts = [{'host': host, 'port': 443}],
http_auth = auth,
use_ssl = True,
verify_certs = True,
connection_class = RequestsHttpConnection
)
呸!现在让我们创建数据:
# Spot the deliberate mistake(s) :D
document1 = {
"title": "Moneyball",
"director": "Bennett Miller",
"year": "2011"
}
document2 = {
"title": "Apollo 13",
"director": "Richie Cunningham",
"year": "1994"
}
data = [document1, document2]
提示!如果需要,请创建索引 -
my_index = 'my_index'
try:
response = client.indices.create(my_index)
print('\nCreating index:')
print(response)
except Exception as e:
# If, for example, my_index already exists, do not much!
print(e)
这就是事情变得有点疯狂的地方。我没有意识到每个批量操作都需要一个,呃,action,例如“索引”、“搜索”等 - 现在让我们定义它
action={
"index": {
"_index": my_index
}
}
下一个怪癖是 OpenSearch 批量 API 需要换行分隔的 JSON(请参阅https://www.ndjson.org),它基本上是将 JSON 序列化为字符串并用换行符分隔。有人在 SO 上写道,这个“奇怪”的 API 看起来像是由数据科学家设计的——我认为这远非冒犯。 (我同意 ndjson 很奇怪。)
可怕的是,现在让我们构建完整的 JSON 字符串,将数据和操作结合起来。一个助手 fn 就在眼前!
def payload_constructor(data,action):
# "All my own work"
action_string = json.dumps(action) + "\n"
payload_string=""
for datum in data:
payload_string += action_string
this_line = json.dumps(datum) + "\n"
payload_string += this_line
return payload_string
好的,现在我们终于可以调用批量 API。我想你可以混合各种动作(这里超出范围) - 去吧!
response=client.bulk(body=payload_constructor(data,action),index=my_index)
这可能是有史以来最无聊的妙语,但你有它。
您也可以直接获取 (geddit) .bulk() 以使用 index= 并将操作设置为:
action={"index": {}}
你好!
现在,选择你的毒药 - 其他解决方案看起来更短更整洁。