blob: d5dc465726d3b62a75c89b83bea436d72fb11416 [file] [log] [blame]
= Using Python
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
Solr includes an output format specifically for <<response-writers.adoc#python-response-writer,Python>>, but <<response-writers.adoc#json-response-writer,JSON output>> is a little more robust.
== Simple Python
Making a query is a simple matter. First, tell Python you will need to make HTTP connections.
[source,python]
----
from urllib2 import *
----
Now open a connection to the server and get a response. The `wt` query parameter tells Solr to return results in a format that Python can understand.
[source,python]
----
connection = urlopen('http://localhost:8983/solr/collection_name/select?q=cheese&wt=python')
response = eval(connection.read())
----
Now interpreting the response is just a matter of pulling out the information that you need.
[source,python]
----
print response['response']['numFound'], "documents found."
# Print the name of each document.
for document in response['response']['docs']:
print " Name =", document['name']
----
== Python with JSON
JSON is a more robust response format, and Python has support for it in its standard library since version 2.6.
Making a query is nearly the same as before. However, notice that the `wt` query parameter is now `json` (which is also the default if no `wt` parameter is specified), and the response is now digested by `json.load()`.
[source,python]
----
from urllib2 import *
import json
connection = urlopen('http://localhost: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']
----