В этом учебном пособии мы изучим, как использовать Go-SDK, официальный Go клиент для Manticore Search.
В случае, если вы хотите пройти интерактивный курс, перейдите сюда .
Установка
Сначала убедимся, что на машине работает экземпляр Manticore. (Если вам нужен курс по установке Manticore Search для определенной ОС, такой как Debian, CentOs, Ubuntu и т.д., вы можете найти его на нашей платформе интерактивных курсов )
searchd --status
root@go-sdk-75b6444c5b-n6ph9:/# searchd --status
Manticore 3.1.0 445e806e@190716 release
Copyright (c) 2001-2016, Andrew Aksyonoff
Copyright (c) 2008-2016, Sphinx Technologies Inc (http://sphinxsearch.com)
Copyright (c) 2017-2019, Manticore Software LTD (http://manticoresearch.com)
using config file '/etc/sphinxsearch/sphinx.conf'...
searchd status
--------------
uptime: 3569
connections: 1
maxed_out: 0
version: 3.1.0 445e806e@190716 release
mysql_version: 5.5.21
command_search: 0
command_excerpt: 0
command_update: 0
command_delete: 0
command_keywords: 0
command_persist: 0
command_status: 1
command_flushattrs: 0
command_set: 0
command_insert: 0
command_replace: 0
command_commit: 0
command_suggest: 0
command_json: 0
command_callpq: 0
agent_connect: 0
agent_retry: 0
queries: 0
dist_queries: 0
workers_total: 30
workers_active: 1
work_queue_length: 1
query_wall: 0.000
query_cpu: OFF
dist_wall: 0.000
dist_local: 0.000
dist_wait: 0.000
query_reads: OFF
query_readkb: OFF
query_readtime: OFF
avg_query_wall: 0.000
avg_query_cpu: OFF
avg_dist_wall: 0.000
avg_dist_local: 0.000
avg_dist_wait: 0.000
avg_query_reads: OFF
avg_query_readkb: OFF
avg_query_readtime: OFF
qcache_max_bytes: 16777216
qcache_thresh_msec: 3000
qcache_ttl_sec: 60
qcache_cached_queries: 0
qcache_used_bytes: 0
qcache_hits: 0
Теперь мы можем установить Go-SDK с помощью следующей команды:
go get github.com/manticoresoftware/go-sdk/manticore
root@go-sdk-75b6444c5b-n6ph9:/# go get github.com/manticoresoftware/go-sddk/manticore
Основное использование
Давайте взглянем на этот простой скрипт на Go:
cat manticore.go
root@go-sdk-75b6444c5b-n6ph9:/# cat manticore.go
package main
import "github.com/manticoresoftware/go-sdk/manticore"
import "fmt"
func main() {
cl := manticore.NewClient()
cl.SetServer("127.0.0.1", 9312)
cl.Open()
res, err := cl.Sphinxql(`replace into testrt values(1,'my subject', 'my content', 15)`)
fmt.Println(res, err)
res, err = cl.Sphinxql(`replace into testrt values(2,'another subject', 'more content', 15)`)
fmt.Println(res, err)
res, err = cl.Sphinxql(`replace into testrt values(5,'again subject', 'one more content', 10)`)
fmt.Println(res, err)
res2, err2 := cl.Query("more|another", "testrt")
fmt.Println(res2, err2)
Скрипт создает нового клиента Manticore, выполняет простые запросы INSERT к индексу testrt, а затем делает запрос на добавленный контент.
Давайте запустим его:
go run manticore.go
root@go-sdk-75b6444c5b-n6ph9:/# go run manticore.go
[Query OK, 1 rows affected]
[Query OK, 1 rows affected]
[Query OK, 1 rows affected]
Status: ok
Query time: 0s
Total: 1
Total found: 1
Schema:
Fields:
title
content
Attributes:
gid: int
Matches:
Doc: 2, Weight: 2, attrs: [15]
Word stats:
'more' (Docs:2, Hits:2)
'another' (Docs:1, Hits:1)
Как видно, новые документы были успешно добавлены в индекс, и два документа, содержащие слова more или another, были найдены по запросу.
Еще пара примеров
С помощью Go-SDK вы можете легко фильтровать результаты ваших запросов по атрибутам индекса.
cat manticore2.go
root@go-sdk-75b6444c5b-n6ph9:/# cat manticore2.go
package main
import "github.com/manticoresoftware/go-sdk/manticore"
import "fmt"
func main() {
cl := manticore.NewClient()
cl.SetServer("127.0.0.1", 9312)
cl.Open()
res, err := cl.Sphinxql(`replace into testrt values(1,'my subject', 'my content', 15)`)
fmt.Println(res, err)
res, err = cl.Sphinxql(`replace into testrt values(2,'another subject', 'more content', 15)`)
fmt.Println(res, err)
res, err = cl.Sphinxql(`replace into testrt values(5,'again subject', 'one more content', 10)`)
fmt.Println(res, err)
q := manticore.NewSearch("content", "testrt", "")
res2, err2 := cl.RunQuery(q)
fmt.Println(res2, err2)
attrValues := []int64{10}
q.AddFilter("gid", attrValues, false)
res2, err2 = cl.RunQuery(q)
fmt.Println(res2, err2)
Этот скрипт создает нового клиента Manticore, выполняет простые запросы INSERT к индексу testrt, а затем делает два запроса, искомых по слову content. Первый запрос получает все документы, так как все документы в индексе теперь содержат это слово. Второй запрос использует фильтр, который мы создали, и получает только документы, содержащие слово content и имеющие атрибут gid, равный 10. В нашем случае, под этими условиями есть только один документ с id=10.
go run manticore2.go
root@go-sdk-75b6444c5b-n6ph9:/# go run manticore2.go
[Query OK, 1 rows affected]
[Query OK, 1 rows affected]
[Query OK, 1 rows affected]
Status: ok
Query time: 0s
Total: 3
Total found: 3
Schema:
Fields:
title
content
Attributes:
gid: int
Matches:
Doc: 1, Weight: 1, attrs: [15]
Doc: 2, Weight: 1, attrs: [15]
Doc: 5, Weight: 1, attrs: [10]
Word stats:
'content' (Docs:3, Hits:3)
Status: ok
Query time: 0s
Total: 1
Total found: 1
Schema:
Fields:
title
content
Attributes:
gid: int
Matches:
Doc: 5, Weight: 1, attrs: [10]
Word stats:
'content' (Docs:3, Hits:3)
Вы также можете использовать выражение, похожее на SQL, для выполнения вашего фильтрации.
cat manticore3.go
root@go-sdk-75b6444c5b-n6ph9:/# cat manticore3.go
package main
import "github.com/manticoresoftware/go-sdk/manticore"
import "fmt"
func main() {
cl := manticore.NewClient()
cl.SetServer("127.0.0.1", 9312)
cl.Open()
res, err := cl.Sphinxql(`replace into testrt values(1,'my subject', 'my content', 15)`)
fmt.Println(res, err)
res, err = cl.Sphinxql(`replace into testrt values(2,'another subject', 'more content', 15)`)
fmt.Println(res, err)
res, err = cl.Sphinxql(`replace into testrt values(5,'again subject', 'one more content', 10)`)
fmt.Println(res, err)
q := manticore.NewSearch("content", "testrt", "")
res2, err2 := cl.RunQuery(q)
fmt.Println(res2, err2)
q.AddFilterExpression("gid > 10 AND gid < 20" , false)
res2, err2 = cl.RunQuery(q)
fmt.Println(res2, err2)
Здесь мы используем выражение gid > 10 AND gid < 20
для фильтрации результата нашего запроса. Как и в предыдущем примере, первый запрос извлекает все документы из индекса, а второй запрос извлекает только документы с gid=15
.
go run manticore3.go
}root@go-sdk-75b6444c5b-n6ph9:/# go run manticore3.go
[Query OK, 1 rows affected]
[Query OK, 1 rows affected]
[Query OK, 1 rows affected]
Статус: ok
Время запроса: 0с
Всего: 3
Всего найдено: 3
Схема:
Поля:
title
content
Атрибуты:
gid: int
Совпадения:
Doc: 1, Weight: 1, attrs: [15]
Doc: 2, Weight: 1, attrs: [15]
Doc: 5, Weight: 1, attrs: [10]
Статистика по словам:
'content' (Docs:3, Hits:3)
Статус: ok
Время запроса: 5ms
Всего: 2
Всего найдено: 2
Схема:
Поля:
title
content
Атрибуты:
gid: int
Совпадения:
Doc: 1, Weight: 1, attrs: [15]
Doc: 2, Weight: 1, attrs: [15]
Статистика по словам:
'content' (Docs:3, Hits:3)
Вы можете найти полную информацию о подключении к Manticore здесь .
Документация Manticore GO-SDK находится здесь .