关于`Elasticsearch.index()`方法,是使用PUT还是POST?

rbpvctlc  于 2023-06-21  发布在  ElasticSearch
关注(0)|答案(1)|浏览(117)

我们正在研究Python库Elasticsearch Python Client,其官方在线文档包含以下将数据摄取到Elastic中的示例。
我们希望使摄取动作幂等,所以我们想知道库的index()方法使用的是PUT还是POST
This reference说:

PUT方法

POST和PUT的区别在于PUT请求是幂等的。...

官网文档示例:

from datetime import datetime
from elasticsearch import Elasticsearch
es = Elasticsearch('https://localhost:9200')

doc = {
    'author': 'author_name',
    'text': 'Interensting content...',
    'timestamp': datetime.now(),
}
resp = es.index(index="test-index", id=1, document=doc)
print(resp['result'])
xyhw6mcr

xyhw6mcr1#

从elasticsearch-py v8.8.0开始,index方法的代码包含:

def index(
    ...
) -> ObjectApiResponse[t.Any]:
    """
    Creates or updates a document in an index.
    ...
    """
    ...
    if index not in SKIP_IN_PATH and id not in SKIP_IN_PATH:
        __path = f"/{_quote(index)}/_doc/{_quote(id)}"
        __method = "PUT"
    elif index not in SKIP_IN_PATH:
        __path = f"/{_quote(index)}/_doc"
        __method = "POST"
    ...
    return self.perform_request(  # type: ignore[return-value]
        __method, __path, params=__query, headers=__headers, body=__body
    )

这似乎表明:

  • 如果指定了id,则为PUT
  • 如果id * not* 指定,则它是POST(并且自动生成文档ID)。

这是Elasticsearch客户端的同步版本。同样的代码出现在客户端AsyncElasticsearch的异步版本上:https://github.com/elastic/elasticsearch-py/blob/v8.8.0/elasticsearch/_async/client/init.py#L2214
至于Elasticsearch上PUT和POST的行为差异,而不是PUT和POST的通用参考,最好查阅Elasticsearch的Index API文档本身:https://www.elastic.co/guide/en/elasticsearch/reference/8.8/docs-index_.html

相关问题