我把我blog的数据(中英文混合)导出, 作为数据来源, 来说明sphinx的使用.

准备数据源
导入数据:
mysql -u root -p test < wp_posts.sql
配置Sphinx
配置data source:
  1. source blog
  2. {
  3. type            =       mysql
  4. sql_host        =       localhost
  5. sql_user        =       root
  6. sql_pass        =       xxxx
  7. sql_db          =       test
  8. sql_port        =       3306
  9. sql_query       =       /
  10. SELECT ID, post_author, UNIX_TIMESTAMP(post_date) as date_added, post_content from wp_posts
  11. sql_attr_uint   =       post_author
  12. sql_attr_timestamp =    date_added
  13. sql_query_info  =       SELECT * FROM wp_posts where ID=$id
  14. }

配置index:

  1. index blog
  2. {
  3. source                                  = blog
  4. path                                    = /usr/local/sphinx/var/data/blog
  5. docinfo                                 = extern
  6. charset_type                    = zh_cn.utf-8
  7. charset_dictpath                = /usr/local/sphinx/dict
  8. }

注意: 字典的目录要加上.

索引
./bin/indexer --config ./etc/sphinx.conf blog
如果没有错误, 会看到:
Coreseek Full Text Server 3.0(beta)
 Copyright (c) 2006-2008 coreseek.com
using config file './etc/sphinx.conf'...
indexing index 'blog'...
collected 165 docs, 0.2 MB
sorted 0.0 Mhits, 100.0% done
total 165 docs, 164834 bytes
total 0.099 sec, 1670067.52 bytes/sec, 1671.75 docs/sec
测试搜索
./bin/search -c ./etc/sphinx.conf -i blog 苹果
输出:
Coreseek Full Text Server 3.0(beta)
Copyright (c) 2006-2008 coreseek.com
using config file './etc/sphinx.conf'...
0x815e1f8index 'blog': query '苹果 ': returned 1 matches of 1 total in 0.005 sec
displaying matches:
1. document=140, weight=1, post_author=1, date_added=Fri Nov 30 11:22:02 2007
ID=140
post_author=1
post_date=2007-11-30 11:22:02
post_date_gmt=2007-11-30 03:22:02
post_content=This is the text of the Commencement address by Steve Jobs, CEO of Apple Computer and of Pixar Animation Studios, delivered on June 12, 2005.
....
{中间的blog贴内容省略}
....
post_title=You've got to find what you love
post_category=0
post_excerpt=
post_status=publish
comment_status=open
ping_status=open
post_password=
post_name=youve-got-to-find-what-you-love
to_ping=
pinged=
post_modified=2008-06-20 11:58:53
post_modified_gmt=2008-06-20 03:58:53
post_content_filtered=
post_parent=0
guid=http://blog.funcat.cn/?p=164
menu_order=0
post_type=post
post_mime_type=
comment_count=0
words:
1. '苹果': 1 documents, 10 hits
启动searchd
./bin/searchd
Coreseek Full Text Server 3.0(beta)
Copyright (c) 2006-2008 coreseek.com
using config file '/usr/local/sphinx/etc/sphinx.conf'...
使用调用API
  1. #!/usr/bin/python
  2. # -*- coding:utf-8 -*-
  3. import sys
  4. if sys.getdefaultencoding() != 'utf-8':
  5. reload(sys)
  6. sys.setdefaultencoding('utf-8')
  7. import web
  8. from web.contrib.template import render_mako
  9. import MySQLdb
  10. from MySQLdb import *
  11. from sphinxapi import *
  12. urls = (
  13. '/', 'index',
  14. )
  15. render = render_mako(
  16. directories=['templates'],
  17. input_encoding='utf-8',
  18. output_encoding='utf-8',
  19. )
  20. app = web.application(urls, globals())
  21. con = MySQLdb.Connect(host="localhost", port=3306, user="root", passwd="xixihaha", db="blogdata")
  22. class index:
  23. def GET(self):
  24. r_info = ''
  25. info = ''
  26. s_result = ''
  27. return render.index(r_info=r_info, e_info=info, s_result=s_result)
  28. def POST(self):
  29. i = web.input()
  30. if i.keyword == '':
  31. raise web.seeohter('/')
  32. e_info = ''
  33. r_info = ''
  34. s_result = ''
  35. q = i.keyword
  36. cl = SphinxClient()
  37. cl.SetServer ( 'localhost', 3312 )
  38. res = cl.Query ( q, 'blog' )
  39. if not res:
  40. e_info = 'query failed: %s' % cl.GetLastError()
  41. if cl.GetLastWarning():
  42. e_info = 'WARNING: %s/n' % cl.GetLastWarning()
  43. if res.has_key('words'):
  44. for info in res['words']:
  45. r_info += '/t/'%s/' found %d times in %d documents<br/>' % (info['word'], info['hits'], info['docs'])
  46. if res.has_key('matches'):
  47. n = 1
  48. s_result = '/nMatches:<br/>'
  49. import time
  50. print res['matches']
  51. for match in res['matches']:
  52. attrsdump = ''
  53. for attr in res['attrs']:
  54. attrname = attr[0]
  55. attrtype = attr[1]
  56. value = match['attrs'][attrname]
  57. if attrtype==SPH_ATTR_TIMESTAMP:
  58. value = time.strftime ( '%Y-%m-%d %H:%M:%S', time.localtime(value) )
  59. attrsdump = '%s, %s=%s' % ( attrsdump, attrname, value )
  60. s_result += '%d. doc_id=%s, weight=%d%s<br/>' % (n, match['id'], match['weight'], attrsdump)
  61. n += 1
  62. Cursor = con.cursor()
  63. Cursor.execute('select post_content from wp_posts where id = %s' % match['id'])
  64. re = Cursor.fetchall()
  65. s_result += re[0][0]
  66. s_result += '<hr/>'
  67. return render.index(r_info=r_info, e_info=info, s_result=s_result)
  68. if __name__ == '__main__':
  69. app.run()

Sphinx的一个应用实例相关推荐

  1. JUnit基础及第一个单元测试实例(JUnit3.8)

    JUnit基础及第一个单元测试实例(JUnit3.8) 单元测试 单元测试(unit testing) ,是指对软件中的最小可测试单元进行检查和验证. 单元测试不是为了证明您是对的,而是为了证明您没有 ...

  2. 每天一个JavaScript实例-apply和call的使用方法

    <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content ...

  3. 每天一个JavaScript实例-获取元素当前高度

    <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content ...

  4. 创建第一个vue实例

    一.vue安装与下载 1. 官网下载  下载地址 选择开发版本 2. 打开sublime,新建vue文件夹,将下载好的代码vue.js放入vue文件夹中. 3. 新建index.html文件,在hea ...

  5. python字典通讯录_Python利用字典将两个通讯录文本合并为一个文本实例

    本文实例主要实现的是利用字典将两个通讯录文本合并为一个文本,具体代码如下: def main(): ftele1=open("d:\TeleAddressBook.txt",&qu ...

  6. python打开一个不存在的文件时-python判断文件是否存在,不存在就创建一个的实例...

    python判断文件是否存在,不存在就创建一个的实例 如下所示: try: f =open("D:/1.txt",'r') f.close() except IOError: f ...

  7. 将oracle冷备份恢复到另外一个数据库实例中

    因更换服务器需要将Oracle数据库转移到另外台Oracle中. 说明: 1.测试环境为:windows server2003 和 oracle 10g. 2.2台服务器安装的程序目录一样,数据目录不 ...

  8. C# WinForm只允许运行一个窗体实例

    大概看了看别人的方法,都是从语法的角度巧妙实现的. 我要实现的目的是dialogForm.Show(); 点击按钮显示对话框窗体,如果窗体没有关闭,再次点击,不重复显示. 我用了个笨方法,就是用一个静 ...

  9. python判断文件是否存在、不存在则创建_python判断文件是否存在,不存在就创建一个的实例...

    python判断文件是否存在,不存在就创建一个的实例 如下所示: try: f =open("D:/1.txt",'r') f.close() except IOError: f ...

最新文章

  1. 系统架构_Linux内核系统架构介绍
  2. denied 虚拟机access_Windows 2008 R2 Administrator access denied解决办法
  3. Windows10,Maven配置 电脑重启失效
  4. 四十、ETL工具的输入步骤
  5. 4K屏幕+5500万像素摄像头,以成未来手机的一大趋势
  6. org.eclipse.e4.core.di.InjectionException:org.eclipse.swt.SWTException: Widget is disposed
  7. 【To Do】LeetCode 28. Implement strStr() 和KMP算法
  8. OpenCV图像 OSG模型 vs2015 摄像头 图像 插入模型
  9. ASP.NET MVC Flash 在线拍照
  10. msdia140.dll 已加载,但对DllRegisterServer 的调用失败, 错误代码: 0x80070005
  11. 解决Oracle安装过程中出现的缺少KEY_XE.reg文件的问题
  12. ps显示暂存盘已满的解决办法
  13. 源码解析zxing条码边距及总宽度计算规则,附java使用zxing生成条形码,并去除条码两边空白
  14. python大游戏_Python开发【项目】:大型模拟战争游戏(外星人入侵)
  15. 做外贸用哪个企业邮箱比较好?大容量外贸企业邮箱哪家好?
  16. ConcurrentHashMap源码深度解析(一)(java8)——不可不知的基本概念(助你拿下源码事半功倍)
  17. Eclipse插件开发GEF
  18. 「干货」项目经理工作流程23步,步步惊心
  19. 音乐播放器下载音乐需要收费
  20. LVS三种工作模式(NAT、DR、TUN)原理及配置

热门文章

  1. 控制字符输出java_令人伤透脑筋的java 输出控制符到底怎么用!
  2. 通过硬件ID精确寻找驱动--摄像头ID篇
  3. 手机开机启动慢是什么原因_手机开机慢,教您手机开机慢怎么办
  4. 保时捷遇最强对手?玛莎拉蒂发布全新SUV;比亚迪壳牌计划合资在深圳运营一万个电动汽车充电终端 | 美通社头条...
  5. php curl post上传图片,PHP中使用CURL发送get/post请求上传图片批处理功能
  6. 苹果修改wifi密码登陆服务器密码,修改wifi密码后,手机还要设置吗?
  7. Rational Test RealTime 测试操作小结
  8. 通行证漫谈(不断补充)
  9. Nexus安卓木马分析报告
  10. cas入门之一 cas 简介