首页
/ Xapit 项目技术文档

Xapit 项目技术文档

2024-12-23 23:44:27作者:咎岭娴Homer

1. 安装指南

1.1 安装 Xapian

首先,您需要安装带有 Ruby 绑定的 Xapian。最简单的方法是通过 Homebrew 安装:

brew install xapian --ruby

注意:此安装与当前安装的 Ruby 版本绑定。如果您使用 RVM,请确保您处于正确的 Ruby 版本中。

1.2 安装 Xapit

将 Xapit 添加到您的 Gemfile 中,并运行 bundle 命令:

gem "xapit", "~> 0.3"

1.3 安装生成器

如果您在 Rails 应用程序中,运行安装生成器:

rails g xapit:install

这将创建一个配置文件和一个用于生产环境的 rackup 文件。

2. 项目的使用说明

2.1 索引

要使模型可搜索,您必须通过 xapit 方法定义一个索引。以下是一个示例:

class Article < ActiveRecord::Base
  xapit do
    text :name, :content
    field :category_id
    sortable :id, :created_at
    facet :author_name, "Author"
  end
end

此索引使模型可以通过多种方式进行搜索。索引会在记录添加或删除时自动更新。您也可以手动重新生成索引:

rake xapit:index

2.2 搜索

使用 search 类方法在索引上执行全文搜索。这将返回一个 Xapit 范围,您可以在此范围内调用其他范围方法,类似于 Active Record 范围。

# 简单全文搜索
@articles = Article.search("phone")

# 全文搜索与基本布尔匹配
@articles = Article.search("phone OR fax NOT email")

# 分页(支持 kaminari 和 will_paginate)
@articles = Article.search("phone").page(10).per_page(20)

# 基于特定字段的搜索
@articles = Article.search("phone").where(:category_id => params[:category_id])

# 搜索多个否定条件
@articles = Article.search("phone").not_where(:category_id => [3, 5, 8])

# 搜索范围条件
@articles = Article.search.where(:released_at => 2.years.ago..Time.now)

# 基于可排序字段的排序
@articles = Article.search("phone").order(:created_at, :desc)

2.3 拼写建议

当存在相似的索引词时,可以使用拼写建议:

<% if @articles.spelling_suggestion %>
  Did you mean <%= link_to @articles.spelling_suggestion, :overwrite_params => { :keywords => @articles.spelling_suggestion } %>?
<% end %>

2.4 分面搜索

分面允许您根据某些属性进一步过滤结果集:

<% for facet in @articles.facets %>
  <%= facet.name %>
  <% for option in facet.options %>
    <%= link_to option.name, :overwrite_params => { :facets => option } %>
    (<%= option.count %>)
  <% end %>
<% end %>

3. 项目API使用文档

3.1 索引API

  • text(:field_name):将字段标记为全文搜索字段。
  • field(:field_name):将字段标记为字段搜索字段。
  • sortable(:field_name):将字段标记为可排序字段。
  • facet(:field_name, "Label"):将字段标记为分面字段。

3.2 搜索API

  • search(query):执行全文搜索。
  • where(conditions):添加条件过滤。
  • not_where(conditions):添加否定条件过滤。
  • order(field, direction):按指定字段排序。
  • page(number):设置分页页码。
  • per_page(number):设置每页显示的记录数。

3.3 拼写建议API

  • spelling_suggestion:获取拼写建议。

3.4 分面API

  • facets:获取分面列表。
  • with_facets(facets):应用分面过滤。
  • applied_facet_options:获取已应用的分面选项。

4. 项目安装方式

4.1 通过 Homebrew 安装 Xapian

brew install xapian --ruby

4.2 通过 Gemfile 安装 Xapit

gem "xapit", "~> 0.3"

4.3 运行安装生成器

rails g xapit:install

4.4 手动重新生成索引

rake xapit:index

通过以上步骤,您可以成功安装并使用 Xapit 项目进行全文搜索。

登录后查看全文
热门项目推荐