Ставим отсюда
https://github.com/FactorAG/django-sphinx
В settings.py
INSTALLED_APS= (
...
'djangosphinx',
...
)
# Sphinx 2.0.4/2.0.6/2.0.8
SPHINX_API_VERSION = 0x119
models.py
from djangosphinx.models import SphinxSearch
class Product(models.Model):
brand = models.ForeignKey(Brand, verbose_name=u'Бренд')
title = models.CharField(_(u'Марка'), max_length=50, blank=True)
caption = models.CharField(_(u'Серия'), max_length=150, blank=True)
composition = models.CharField(_(u'Ингредиенты'), max_length=60, blank=True, null=True)
about = RichTextField(_(u'Описание'), blank=True)
pub_date = models.DateTimeField(default=datetime.now)
pet = models.ManyToManyField(Pet, verbose_name=u'Животное')
updated = models.DateTimeField(auto_now=True)
search = SphinxSearch(weights={'title': 90, 'caption': 80, 'about': 100, 'composition': 70},
mode='SPH_MATCH_ALL', rankmode="SPH_RANK_BM25", sort='SPH_SORT_RELEVANCE',
)
views.py
@render_to('core/entry_list.html')
def searcher(request):
if 'srch' in request.GET and request.GET['srch']:
txt = request.GET['srch']
entries = Product.search.query(txt)
return {'object_list': entries, }
else:
return root(request)
django-sphinx умеет создавать конфигурацию для Sphinx
./manage.py generate_sphinx_config <app_name> > config/sphinx.conf
Получившийся файл конфигурации нужно немного дополнить
source core_product
{
type = mysql
sql_host =
sql_user = <DB_user>
sql_pass = ******
sql_db = <DB>
sql_port =
sql_query_pre = SET NAMES utf8
sql_query_post =
sql_query = \
SELECT id, onmain, brand_id, title, caption, gen_caption, composition, about, ext, pub_date, updated\
FROM core_product
sql_query_info = SELECT * FROM `core_product` WHERE `id` = $id
# ForeignKey's
sql_attr_uint = brand_id
# DateField's and DateTimeField's
sql_attr_timestamp = pub_date
sql_attr_timestamp = updated
}
index core_product
{
source = core_product
path = /home/project/var/sphinx
docinfo = extern
morphology = stem_enru, Soundex, Metaphone
charset_type = utf-8
min_word_len = 2
min_infix_len = 2
min_prefix_len = 0
enable_star = 1
charset_table = 0..9, A..Z->a..z, _, a..z, U+0401->U+0435, U+0451->U+0435, U+410..U+42F->U+430..U+44F, U+430..U+44F
index_exact_words = 1
expand_keywords = 1
index_sp=1
html_index_attrs = img=alt,title; a=title;
html_strip=1
}
indexer {
mem_limit = 64M
}
searchd {
listen = 9312
listen = 9306:mysql41
log = /home/project/logs/searchd.log
query_log = /project/logs/query.log
read_timeout = 5
client_timeout = 300
max_children = 30
pid_file = /home/project/tmp/searchd.pid
max_matches = 1000
seamless_rotate = 1
preopen_indexes = 1
unlink_old = 1
mva_updates_pool = 1M
max_packet_size = 8M
max_filters = 256
max_filter_values = 4096
max_batch_queries = 32
workers = threads
}
Стваим Sphinx
- Качаем исходники (есть готовые пакеты) отсюда
http://sphinxsearch.com/downloads/release/
- Распаковываем и конфигурируем
tar xzvf sphinx-2.0.8-release.tar.gz
sphinx-2.0.8-release
./configure --with-mysql
make
- Осталось собрать пакет и установить его в ситему (никогда не делайте make install, каждый раз, когда вы так делаете, умирает котенок)
aptitude install checkinstall
checkinstall
теперь вы можете управлять пакетом с помощью пакетного менеджера.
Sphinx установлен, осталось проиндексировать БД и запустить демона.
indexer --config config/sphinx.conf --all
Для дальнейшей индексации можно использовать
indexer --config config/sphinx.conf --all --rotate
Для запуска
searchd -c config/sphinx.conf
Для остановки
searchd --stop -c config/sphinx.conf
Для повышения качества поиска можно использовать словарь словоформ
aptitude install myspell-ru
spelldump /usr/share/hunspell/ru_RU.dic /usr/share/hunspell/ru_RU.aff wordforms_ru_RU.txt
cat wordforms_ru_RU.txt | enca -L ru
iconv -f KOI8-R -t UTF-8 -o wordforms_ru_RU_UTF8.txt wordforms_ru_RU.txt
Затем подключаем его в sphinx.conf в раздел index
wordforms = /path/to/wordforms_ru_RU_UTF8.txt
Источники
http://sphinxsearch.com/docs/manual-2.0.8.html#supported-system
http://osmanov-dev-notes.blogspot.ru/2011/06/how-to-create-sphinx-wordform.html
http://proft.me/2011/01/22/polnotekstovyj-poisk-v-django/
http://habrahabr.ru/post/136261/
http://habrahabr.ru/post/147745/
http://habrahabr.ru/post/132118/