-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy path2010-03-04-728.html
More file actions
74 lines (72 loc) · 3.18 KB
/
2010-03-04-728.html
File metadata and controls
74 lines (72 loc) · 3.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
---
layout: post
title: "Rails与Sphinx的整合"
---
如何在 Rails 项目里添加全文索引功能呢。下面介绍一下用sphinx-for-chinese 提供的Rails插件给Rails项目添加全文索引的过程
<span id="more-728"></span>
前提是你的机器上已经成功安装了 Sphinx-for-chinese,如果还没有安装,可以参考 <a href="/2010/03/04/720.html" target="_blank">Debian/Linux下 sphinx-for-chinese的安装</a>
<ol>
<li> 创建项目目录
<pre>$ rails --database=mysql demo
$ cd demo</pre>
</li>
<li>修改 config/database.yml文件,添加连接数据库的信息
<pre>development:
adapter: mysql
encoding: utf8
reconnect: false
database: demo_development
pool: 5
<strong>username: user
password: pass</strong>
socket: /var/run/mysqld/mysqld.sock</pre>
说明:加粗部分是添加的</li>
<li>创建数据库
<pre>demo$ rake db:create RAILS_ENV='development'</pre>
</li>
<li>创建搜索控制器
<pre>demo$ ruby script/generate controller search index result</pre>
</li>
<li>修改 app/controllers/search_controller.rb 文件
<pre>class SearchController < ApplicationController
def index
end
def result
<strong>@query = params['query']
@sphinx = Sphinx::Client.new
@results = @sphinx.Query(@query)</strong>
end
end</pre>
说明:加粗部分是添加的</li>
<li>修改 app/views/search/index.html.erb 文件,以下是修改后的文件内容
<pre><% form_tag :action =>'result' do %>
<%= text_field_tag :query,'' %>
<%= submit_tag '查询' %>
<% end %></pre>
</li>
<li>修改 app/views/search/result.html.erb 文件,以下是修改后的文件内容
<pre>搜索 <strong><%= @query %></strong> 获得 <%= @results['total_found'] %> 条匹配结果,用时 <%= @results['time'] %>秒。</br>
<legend>查询统计:</legend>
<% @results['words'].each do |word, info| %>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong><%= word%></strong>在总共 <%= info['docs']%> 个文档中命中 <%= info['hits']%> 次。
<% end %>
<ol>
<% @results['matches'].each do |doc| %>
<li>doc_id=<%= doc['id']%>, weight=<%= doc['weight']%>
<% doc['attrs'].each do |attr, value|
%>, <%= attr%>=<%= value%>
<% end %></li>
<% end %>
</ol></pre>
</li>
<li>启动服务
<pre>demo$ ruby script/server</pre>
打开浏览器,输入 http://3000/search 你就可要看到一个搜索框,输入查询关键字,点击“查询”按钮就可以看到搜索结果。
以下是我使用 sphinx-for-chinese自带的测试数据截的图。
<ul>
<li>查询界面截图
<a href="/wpfiles/2010/03/search.png"><img class="aligncenter size-medium wp-image-729" title="search" src="/wpfiles/2010/03/search-300x200.png" alt="搜索界面截图" width="300" height="200" /></a></li>
<li>查询结果界面截图<a href="/wpfiles/2010/03/result.png"><img class="aligncenter size-medium wp-image-733" title="result" src="/wpfiles/2010/03/result-300x198.png" alt="搜索结果截图" width="300" height="198" /></a></li>
</ul>
</li>
</ol>