curl到python请求solr查询的转换

yiytaume  于 2023-03-18  发布在  Solr
关注(0)|答案(1)|浏览(162)

我遇到了一个小问题,我有一个solr索引,我使用curl查询它,如下所示:

curl 'http://localhost:8984/solr/my_index/select?indent=on&q="galvin%20life%20sciences"~0&wt=json&sort=_docid_%20desc&rows=5'

得到(注意q字符串和用于邻近搜索的代字号运算符):

{
  "responseHeader":{
    "status":0,
    "QTime":1,
    "params":{
      "q":"\"galvin life sciences\"~0",
      "indent":"on",
      "sort":"_docid_ desc",
      "rows":"5",
      "wt":"json"}},
  "response":{"numFound":61,"start":0,"numFoundExact":true,"docs":[

现在,我尝试在python中复制相同的东西,使用:

resp=requests.get('http://localhost:8984/solr/my_index/select?q=' + "galvin%20life%20sciences"+"~0" + '&wt=json&rows=5&start=0&fl=id,org*,score')

然后我得到了这个

[
    {
        "responseHeader": {
            "status": 0,
            "QTime": 0,
            "params": {
                "q": "galvin life sciences~0",
                "fl": "id,org*,score",
                "start": "0",
                "rows": "5",
                "wt": "json"
            }
        },
        "response": {
            "numFound": 3505398,
            "start": 0,
            "maxScore": 9.792607,
            "numFoundExact": true,
            "docs": [

您可以看到这些查询有些不同:

curl: "q":"\"galvin life sciences\"~0",
requests: "q": "galvin life sciences~0",

所以我在使用请求时得到了错误的结果。
我不确定我应该在请求中做些什么来使查询匹配。
我试过@Mats的解决方案:

requests.get('http://localhost:8984/solr/my_index/select', params={
  'q': '"galvin life sciences"~0',
  'wt': 'json',
  'rows': 5,
  'start': 0,
  'fl': 'id,org*,score',
})

但是现在我不能把变量传递给它(多么烦人)。所以我有:

q_solr="Galvin life sciences"
requests.get('http://localhost:8984/solr/my_index/select', params={
  'q': q_solr+'~0',
  'wt': 'json',
  'rows': 5,
  'start': 0,
  'fl': 'id,org*,score',
})

但是这没有给我任何结果。。WTAF!!!

2o7dmzc5

2o7dmzc51#

您可以使用requests内置支持来创建URL参数(这是我的推荐,因为它可以让您正确地分离参数和请求处理转义):

requests.get('http://localhost:8984/solr/my_index/select', params={
  'q': '"galvin life sciences"~0',
  'wt': 'json',
  'rows': 5,
  'start': 0,
  'fl': 'id,org*,score',
})

否则,你可以像以前那样自己构建URL,但是由于你已经连接了字符串,而不是将"包含在前一个字符串中,所以你只是将q=galvin ..合并,而不是与"galvin合并。如果下一个字符串包含在内,就不需要结束前一个字符串。如果需要,你也可以使用反斜杠来转义字符串中的任何引号。

resp=requests.get('http://localhost:8984/solr/my_index/select?q="galvin%20life%20sciences"~0&wt=json&rows=5&start=0&fl=id,org*,score')

但是使用第一种形式,除非您从不同的来源获得预先格式化的URL。

相关问题