Using Python to Operate Sphinx
The third-party library 'sphinxapi' can be used to operate Sphinx database connections and perform data insertion, querying, modification, and deletion in Python. This library provides an API for interacting with the Sphinx Search engine.
The following is an example code that shows how to use Python to operate Sphinx database connections and perform data insertion, query, modification, and deletion:
python
import sphinxapi
#Connect to the Sphinx Search engine
sphinx_conn = sphinxapi.SphinxClient()
Sphinx_ Conn. SetServer ('localhost ', 9312) # Set Connection Address and Port
#Data insertion
index = 'my_index'
sphinx_conn.AddQuery('INSERT INTO {} (id, title, content) VALUES (1, "example", "example content")'.format(index))
#Data Query
sphinx_conn.AddQuery('SELECT * FROM {} WHERE MATCH("example")'.format(index))
result = sphinx_conn.RunQueries()
#Process query results
if result and 'error' not in result[0]:
matches = result[0]['matches']
for match in matches:
print('ID:', match['id'])
print('Title:', match['attrs']['title'])
print('Content:', match['attrs']['content'])
else:
Print ('Query failed ')
#Data modification
sphinx_conn.AddQuery('UPDATE {} SET title="updated" WHERE id=1'.format(index))
sphinx_conn.RunQueries()
#Data deletion
sphinx_conn.AddQuery('DELETE FROM {} WHERE id=1'.format(index))
sphinx_conn.RunQueries()
In the above code, we first use 'sphinxapi. SpinxClient()' to create a connection to the Sphinx engine, and use 'sphinx'_ Conn. SetServer() ` Set the connection address and port.
Then, we can use ` sphinx_ Conn. AddQuery() 'method to execute Sphinx SQL statements. In the insertion example, we use the 'Insert INTO' statement to add data to the specified index. In the query example, we use the 'SELECT *' statement to match specific keywords. In the modification example, we use the 'UPDATE' statement to update the data for the specified condition. In the deletion example, we use the 'DELETE FROM' statement to delete data with specified conditions.
Finally, we use ` sphinx_ Conn. RunQueries() 'to execute these SQL statements and use the returned results for further processing. The processing in the above code is a simple printing result.
It should be noted that in order to run the above code, you need to first install the 'sphinxapi' library. You can use the 'pip' tool for installation, with the following commands:
pip install sphinxapi
I hope this example can help you start using Python to operate Sphinx database connections and perform data insertion, querying, modification, and deletion.