Django数据库后端,用于SphinxQL。
项目描述
这是一个SmartFile开源项目。了解更多关于SmartFile如何使用和贡献开源软件的信息。
简介
这是一个简单的Django数据库后端,允许通过SphinxQL与Sphinx交互。它基本上是默认的Django MySQL后端,针对Sphinx进行了一些更改。
SphinxQL是Sphinx searchd支持的一个MySQL克隆模式。它允许您使用常规旧SQL语法查询索引。如果您使用实时索引,您还可以在索引中添加和更新文档。
此后端旨在配置为Django settings.py中的数据库。
此包提供Manager类、SQLCompiler套件和相关代码,以实现此功能。
使用方法
首先,您必须在Django配置中定义一个数据库连接。您还必须安装Sphinx数据库路由器,并将django_sphinx_db添加到您的INSTALLED_APPS列表中。
# Install django_sphinx_db: INSTALLED_APPS += ('django_sphinx_db', ) # This is the name of the sphinx server in DATABASES: SPHINX_DATABASE_NAME = 'sphinx' # Define the connection to Sphinx DATABASES = { 'default': { # Your default database connection goes here... }, SPHINX_DATABASE_NAME: { 'ENGINE': 'django_sphinx_db.backend.sphinx', # The database name does not matter. 'NAME': '', # There is no user name or password. 'USER': '', 'PASSWORD': '', # Don't use localhost, this will result in using a UDS instead of TCP... 'HOST': '127.0.0.1', 'PORT': '9306', }, } # ... and route accordingly ... DATABASE_ROUTERS = ( 'django_sphinx_db.routers.SphinxRouter', ) ```
然后定义一个从SphinxModel派生的模型。像往常一样,模型将放在models.py中。
from django_sphinx_db.backend.models import SphinxModel, SphinxField class MyIndex(SphinxModel): class Meta: # This next bit is important, you don't want Django to manage # the table for this model. managed = False name = SphinxField() content = SphinxField() date = models.DateTimeField() size = models.IntegerField()
配置Sphinx
现在您需要为您的主索引生成一个配置文件。提供了一个管理命令,可以将模型定义转换为合适的配置。
$ python manage.py syncsphinx >> /etc/sphinx.conf $ vi /etc/sphinx.conf
生成的配置文件应该是一个良好的起点,但是,强烈建议您对照[Sphinx配置参考](http://sphinxsearch.com/docs/2.0.2/confgroup-index.html)进行配置审查。
使用Django ORM与Sphinx
您现在可以使用Django ORM查询和管理您的实时索引。您可以使用以下方法在索引中插入和更新文档。以下示例使用[全文库](https://github.com/btimby/fulltext)将文件内容读取为纯文本。
import os, time, fulltext # Add a document to the index. path = 'resume.doc' st = os.stat(path) MyIndex.objects.create( name = path, content = fulltext.get(path, ''), size = st.st_size, date = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(st.st_mtime)), ) # Update a document in the index doc = MyIndex.objects.get(pk=1) doc.content = fulltext.get(path, '') doc.size = st.st_size doc.date = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(st.st_mtime)) doc.save()
您可以使用Django的< cite>搜索 cite>运算符执行全文查询。有关更多信息,请参阅Django文档。
MyIndex.objects.filter(content__search='Foobar')
查询将直接传递给Sphinx,因此尊重Sphinx扩展查询语法。
单元测试
Django的Sphinx后端将忽略create_test_db和destroy_test_db调用。当配置Sphinx数据库时,这些调用将失败,阻止您运行测试。但是,这意味着任何配置的Sphinx数据库将在测试期间使用。只要您考虑这一点编写测试,就不应该有问题。请记住,您可以使用TEST_NAME数据库连接参数在测试运行期间将查询重定向到不同的数据库连接。