Searching Sphinx from Python

The Sphinx application includes a Python API interface that allows you to perform searches and return results in Python programs. All of the API commands are defined in the Sphinx documentation, but their specific usage within Python can vary.

We will take a quick tour of the Sphinx Python API and then discuss how it can be integrated into our Django models. First, a simple Python snippet that generates the interface to a Sphinx server running on our local machine:

SERVER = 'localhost'
PORT = 5555
client = sphinxapi.SphinxClient()
client.setServer(SERVER, PORT)

Now we have a client object that exposes the API listed in the Sphinx documentation. We can perform simple operations, like queries, using this client. To replicate the command line we used in the previous section, we could issue the following Python command:

results = client.Query('cranberry juice')

If we need to specify the index or indexes to use, we can pass them as a string containing the index names separated by commas as shown:

results = client.Query('cranberry juice', 'products_product, products_other')

The results variable can be accessed like a dictionary to retrieve information about the search results:

total_hits = results['total']
matches = results['matches']

We can now access the columns for each of our results in the matches variable to load the primary key values:

keys = [r['attrs']['id'] for r in matches]

We could go on from here by using these primary key values to find a QuerySet in our Django model for this table. But this is quickly getting complicated and the performance of doing it this way is not good. Fortunately, the Django community includes an application for Sphinx that wraps all of this functionality into a simple tool. It is called django-sphinx and was written by David Cramer.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset