Sphinx Client API используется для взаимодействия с демоном searchd и получения данных от Sphinx. Он используется в больших приложениях, оперирующих огромными объемами данных, для реализации быстрого и релевантного поиска. Ruby API — это портированный PHP API, который можно найти в дистрибутиве Sphinx. Ниже вы найдете информацию о том, как установить и использовать API.
Предупреждение: Если Вы использовали плагин до выхода версии 0.3.0, проверьте документацию, так как я убрал различия между реализацией API на PHP и Ruby, а потому все фукнции были переименованы.
Установка
Sphinx Client API для Ruby реализован как плагин для Ruby on Rails (но Вы также можете использовать его в автономных приложениях на Ruby, зависимостей от других библиотек нет). Все, что нужно – это загрузить исходный код плагина и распаковать его в каталог vendor/plugins/sphinx.
Документация
Вы можете найти документацию здесь. Кроме того, можно самостоятельно построить документацию, выполнив следующую команду в каталоге vendor/plugins/sphinx:
1 | rake rdoc |
Вот короткий пример использования:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | @sphinx = Sphinx::Client.new @sphinx.SetSortMode(Sphinx::Client::SPH_SORT_ATTR_ASC, 'created_at') results = @sphinx.Query('test') puts "Searched for:" results['words'].each do |word, info| puts " #{word} found #{info['hits']} times in #{info['docs']} documents" end print "\nResults #{results['total']} of #{results['total_found']}; " puts "Total time: #{results['time']}" results['matches'].each do |doc| puts "Document ##{doc['id']} (weight #{doc['weight']}):" doc['attrs'].each do |attr, value| puts " #{attr}: #{value}" end end |
Загрузка
Последняя версия “Sphinx Client API” — 0.3.1, и она может быть загружена отсюда:
version0.3.1DownloadSphinx Client API
Кроме того, вы можете скачать библиотеку для текущего нестабильного снапшота Sphinx 0.9.8 r1112 здесь: Sphinx Client API v0.4.0-r1112. ПРЕДУПРЕЖДЕНИЕ: это версия находится в разработке, она недостаточно протестирована и не готова к релизу. Даже если она уже используется на живых сайтах, в ней все еще есть ошибки, возможно критические. Используйте ее на свой страх и риск, и сообщайте обо всех проблемах, с которыми вы столкнулись.
Если у Вас есть предложения, Вы хотите оставить отзыв или нашли ошибки, пожалуйста, отпишитесь в комментариях. Это очень важно для меня!
Список изменений
- v0.3.1 (9 декабря 2007)
- Исправлена ошибка с порядком сортировки результатов поиска.
- v0.3.0 (3 апреля 2007)
- Исправлена ошибка с обработкой атрибутов в результатах запроса (спасибо shawn).
- Исправлена ошибка с округлением временем обработки запроса (спасибо michael).
- Обновлено API в соответствии с PHP API для Sphinx 0.9.7.
- Добавлены тесты RSpec
- v0.2.0 (20 декабря 2006)
- Улучшена обработка исключений.
- Обновлено API в соответствии с PHP API для Sphinx 0.9.7 RC2.
- v0.1.0 (26 ноября 2006)
- Базовая реализация библиотеки.
Другие плагины
Полный список плагинов, которые я написал, можно найти здесь.

Hi, I have a huge data in MySQl. Before I found Sphinx, I intend to build my old indexes and then build a tag cloud base on those indexes.
Now I wonder, can Sphinx and Client API help me in building tag cloud base on Sphinx indexes ?
Sorry, in the previous comment. I mean “my own indexes”, not “my old indexes”.
My English is not good :D !
[...] – Rails wrapper for Ruby API for Sphinx, a full-text search [...]
[...] I have a good news: Sphinx Client API has been updated and now it supports all brand new features of the unstable Sphinx 0.9.8 development snapshot. What does it mean for you as a developer? What features you will get if you would decide to switch to the new version? I will describe most valuable improvements of the Sphinx in this article, and will show how to use them with new Sphinx Client API 0.4.0 r909. [...]
[...] ruby/rails plugin rather than trying to reinvent the wheel. I found two plugins; acts_as_sphinx and Sphinx Client API for Ruby (SCAFR). They are both very similar except acts_as_sphinx has act methods to load models from the [...]
Wanted to let you know I used your API with some refactoring in my project. Pls see my post for more information at http://www.weebadde.com/?p=8. I am happy contribute the refactored code.
Hi!
This is my port of BuildKeywords Sphinx function from sphinxapi.php. Maybe you find it interesting and include it in future versions of your plugin.
—-
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
75
76
77
78
79
80
81
#
# Author:: Leonid S. Pavlov <mailto:leonid.pavlov at gmail dot com>.
# Copyright:: Copyright (c) 2008 Leonid S. Pavlov
# License:: Distributes under the same terms as Ruby
module Sphinx
class Client
SEARCHD_COMMAND_KEYWORDS = 3
VER_COMMAND_KEYWORDS = 0x100
# Keywords generation
#
# Connect to searchd server, and generate keyword list for a given query.
#
# * <tt>query</tt> is query string
# * <tt>index</tt> is index name (or names) to query
# * <tt>hits</tt> is the bool flag for counting words hits in indexed documents
#
# Returns an array of words on success.
# Returns false on failure.
#
# Usage example:
# sphinx.BuildKeywords('test1', '*', true)
#
def BuildKeywords(query, index, hits)
assert { query.instance_of? String }
assert { index.instance_of? String }
assert { hits.instance_of?(TrueClass) || hits.instance_of?(FalseClass) }
sock = self.Connect
# build request
request = Request.new # v.1.0 req
request.put_string query # req query
request.put_string index # req index
request.put_int hits ? 1 : 0 # req hits
# send query, get response
len = request.to_s.length
request = [SEARCHD_COMMAND_KEYWORDS, VER_COMMAND_KEYWORDS, len].pack('nnN') + request.to_s # add header
sock.send(request, 0)
response = GetResponse(sock, VER_COMMAND_KEYWORDS)
# parse response
pos = 0
res = []
rlen = response.length
nwords = response[pos, 4].unpack('N*').first
pos += 4
for i in 0...nwords do
len = response[pos, 4].unpack('N*').first; pos += 4
tokenized = response[pos, len]
pos += len;
len = response[pos, 4].unpack('N*').first; pos += 4
normalized = response[pos, len]
pos += len;
res << { 'tokenized' => tokenized, 'normalized' => normalized }
if (hits)
ndocs, nhits = response[pos, 8].unpack('N*N*')
pos += 8
res[i].merge!('docs' => ndocs, 'hits' => nhits)
end
if pos > rlen
@error = 'incomplete reply'
raise SphinxResponseError, @error
end
end
return res
end
end
end
забавый баг на стыке CodeColorer’а и Google Reader’а:
текст внутри колореровского контейнера “тянется” под следующие посты в ридере… с чего бы это?
[...] your users’ searches, sphinx and memcache. Spice and stuff: a good ruby sphinx api – try this. You’ll also need a decent memcache api in ruby – go for the creators’ recommendation, [...]
[...] and stuff: a good ruby sphinx api – try this. You’ll also need a decent memcache api in ruby – go for the creators’ recommendation, [...]
I’ve tried to download the 0.4 version of the client API as seen in http://kpumuk.info/ror-plugins/sphinx-client-api-0-3-1-and-0-4-0-r909-for-sphinx-0-9-8-r909-released/, where says “go to project page” (here). Always downloads 0.3.1 version. Can you please guide me to the latest version, please?
[...] ruby/rails plugin rather than trying to reinvent the wheel. I found two plugins; acts_as_sphinx and Sphinx Client API for Ruby (SCAFR). They are both very similar except acts_as_sphinx has act methods to load models from the [...]