I have a RESTful API that I have exposed using an implementation of Elasticsearch on an EC2 instance to index a corpus of content. I can query the search by running the following from my terminal (MacOSX):

curl -XGET 'http://ES_search_demo.com/document/record/_search?pretty=true' -d '{
  "query": {
    "bool": {
      "must": [
        {
          "text": {
            "record.document": "SOME_JOURNAL"
          }
        },
        {
          "text": {
            "record.articleTitle": "farmers"
          }
        }
      ],
      "must_not": [],
      "should": []
    }
  },
  "from": 0,
  "size": 50,
  "sort": [],
  "facets": {}
}'

How do I turn above into a API request using python/requests or python/urllib2 (not sure which one to go for - have been using urllib2, but hear that requests is better...)? Do I pass as a header or otherwise?

推荐答案

Using requests:

import requests
url = 'http://ES_search_demo.com/document/record/_search?pretty=true'
data = '''{
  "query": {
    "bool": {
      "must": [
        {
          "text": {
            "record.document": "SOME_JOURNAL"
          }
        },
        {
          "text": {
            "record.articleTitle": "farmers"
          }
        }
      ],
      "must_not": [],
      "should": []
    }
  },
  "from": 0,
  "size": 50,
  "sort": [],
  "facets": {}
}'''
response = requests.post(url, data=data)

Depending on what kind of response your API returns, you will then probably want to look at response.text or response.json() (or possibly inspect response.status_code first). See the quickstart docs here, especially this section.

Python相关问答推荐

在Admin中显示从ManyToMany通过模型的筛选结果

干燥化与列姆化的比较

提高算法效率的策略?

Flask运行时无法在Python中打印到控制台

使用SQLAlchemy从多线程Python应用程序在postgr中插入多行的最佳方法是什么?'

如何使用pytest在traceback中找到特定的异常

如何在Python中从html页面中提取html链接?

如何在python tkinter中绑定键盘上的另一个回车?

使用Scikit的ValueError-了解

使用Django标签显示信息

as_index=False groupBy不支持count

以元组为索引的Numpy多维索引

条件Python Polars cum_sum over a group,有更好的方法吗?

通过PyTorch中的MIN函数传递渐变

matplotlib散点图与NaNs和cmap colored颜色 矩阵

为什么Python多处理.Process()传递队列参数并且读取比函数传递队列参数和读取更快?

当使用随机均匀(a,b)时,b是包含的还是排他的?

Selify urllib.error.HTTPError:HTTP错误404:未找到

聚合数据帧的n个连续行的惯用方式

如何对 torch 张量中的数据进行切片?