Django配置haystack、Woosh或ElasticSearch、jieba

不多说直接上代码

项目名:first    app名称:info

目录结构:

项目setting.py:

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'haystack',#在你自定义的app的上面
    'info',
)
#并添加Woosh全文搜索引擎
HAYSTACK_CONNECTIONS = {
    'default': {
        'ENGINE': 'haystack.backends.whoosh_cn_backend.WhooshEngine',
        'PATH': os.path.join(BASE_DIR, 'whoosh_index'),
    }
}
# 自动生成索引
HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
项目的urls.py:

url(r'^info/', include('info.urls')),

models:

from django.db import models

# Create your models here.
class Info(models.Model):
    _id=models.CharField(max_length=20)
    _score=models.CharField(max_length=11)
    number=models.CharField(max_length=40)
    singer=models.CharField(max_length=20)
    size=models.CharField(max_length=40)
    song=models.CharField(max_length=40)
    tag=models.CharField(max_length=20)
    timelen=models.CharField(max_length=20)

search_indexes.py

# coding=utf-8
from haystack import indexes
from models import Info # 引入你项目下的model(也就是你要将其作为检索关键词的models)

class InfoIndex(indexes.SearchIndex, indexes.Indexable):# 类名必须为需要检索的Model_name+Index,这里需要检索Note,所以创建NoteIndex
    text = indexes.CharField(document=True, use_template=True)#这句话不要改,都要用这句话,和字段无关

    def get_model(self):
        return Info

    def index_queryset(self, using=None):
        return self.get_model().objects.all()  # 可对数据进行检索限制
search_views.py:

#-*- coding: utf-8 -*-
from haystack.views import SearchView
from .models import *

class MySeachView(SearchView):
    def extra_context(self):  # 重载extra_context来添加额外的context内容
        context = super(MySeachView, self).extra_context()
        side_list = Info.objects.filter()
        context['side_list'] = side_list
        return context
urls.py:

# -*- coding: utf-8 -*-
from django.conf.urls import url, include
#
# from info import search_views
from info.views import MySeachView
from .import views
urlpatterns=[
    url(r'^list/$',views.list),
    url(r'^search/', MySeachView()),
    # url(r'^search/', include('haystack.urls')),#因为需要自定义搜索结果页面,所以不交给haystack处理
]
views.py:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
from haystack.views import SearchView
from .models import *

class MySeachView(SearchView):
    def extra_context(self):  # 重载extra_context来添加额外的context内容
        context = super(MySeachView, self).extra_context()
        side_list = Info.objects.filter()
        # side_list = Info.objects.filter(number='32768')
        context['side_list'] = side_list
        return context

search.html:

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<form method='get' action="/info/search/" target="_blank">
    <input type="text" name="q">
    <input type="submit" value="查询">
</form>
{% if query %}
    <h3>搜索结果如下:</h3>
    {% for result in page.object_list %}
        {{ result.object.singer }} — 《{{ result.object.song }}》<br/>
    {% empty %}
        <p>啥也没找到</p>
    {% endfor %}

    {% if page.has_previous or page.has_next %}
        <div>
            {% if page.has_previous %}<a href="?q={{ query }}&page={{ page.previous_page_number }}">{% endif %}« 上一页{% if page.has_previous %}</a>{% endif %}
        |
            {% if page.has_next %}<a href="?q={{ query }}&page={{ page.next_page_number }}">{% endif %}下一页 »{% if page.has_next %}</a>{% endif %}
        </div>
    {% endif %}
{% endif %}
</body>
</html>
info_text.txt

{{ object.singer }}
{{ object.song }}

数据库表sql:

DROP TABLE IF EXISTS `info_info`;

CREATE TABLE `info_info` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `_id` varchar(20) NOT NULL,
  `_score` varchar(11) NOT NULL,
  `number` varchar(40) NOT NULL,
  `singer` varchar(20) NOT NULL,
  `size` varchar(40) NOT NULL,
  `song` varchar(40) NOT NULL,
  `tag` varchar(20) NOT NULL,
  `timelen` varchar(20) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;

/*Data for the table `info_info` */

insert  into `info_info`(`id`,`_id`,`_score`,`number`,`singer`,`size`,`song`,`tag`,`timelen`) values (1,'1','98','201','汪峰 庾澄庆','38','我爱你中国','中国好声音-第三季','344'),(2,'2','92','202','那英 周杰伦','41','爱我你就抱抱我','中国好声音-第三季','401'),(3,'3','88','203','杨坤 汪峰','48','我在中国吃着炸鸡','中国好声音-第二季','502'),(4,'4','60','204','庾澄庆 刘欢','34','情非得已','中国好声音-第二季','342'),(5,'5','88','205','杨坤 汪峰','45','爱情是一颗幸福的子弹','中国好声音-第四季','428'),(6,'6','34','206','刘欢 那英','35','征服','中国好声音-第三季','332');

至此代码全部结束,根据参考网站,直接配置jieba分词即可,然后直接访问/info/search/ 搜索即可。

参考文章:

http://blog.csdn.net/ac_hell/article/details/52875927

http://blog.csdn.net/zhaogeno1/article/details/78965298







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值