Python

Solr 包含專為 Python 回應寫入器 設計的輸出格式,但 JSON 回應寫入器 功能更強大一些。

簡單 Python

發出查詢是很簡單的事情。首先,告訴 Python 您需要建立 HTTP 連線。

from urllib2 import *

現在開啟與伺服器的連線並取得回應。`wt` 查詢參數告訴 Solr 以 Python 可以理解的格式傳回結果。

connection = urlopen('https://127.0.0.1:8983/solr/collection_name/select?q=cheese&wt=python')
response = eval(connection.read())

現在解讀回應只需提取您需要的資訊即可。

print response['response']['numFound'], "documents found."

# Print the name of each document.

for document in response['response']['docs']:
  print "  Name =", document['name']

使用 JSON 的 Python

JSON 是一種更強大的回應格式,而且自 2.6 版以來,Python 的標準程式庫已支援此格式。

發出查詢幾乎與之前相同。但是,請注意 `wt` 查詢參數現在是 `json`(如果未指定 `wt` 參數,這也是預設值),而回應現在由 `json.load()` 消化。

from urllib2 import *
import json
connection = urlopen('https://127.0.0.1:8983/solr/collection_name/select?q=cheese&wt=json')
response = json.load(connection)
print response['response']['numFound'], "documents found."

# Print the name of each document.

for document in response['response']['docs']:
  print "  Name =", document['name']