redisearch

package
v1.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 22, 2021 License: BSD-3-Clause Imports: 12 Imported by: 65

Documentation

Index

Examples

Constants

View Source
const (
	// GroupByReducerCount is an alias for GROUPBY reducer COUNT
	GroupByReducerCount = GroupByReducers("COUNT")

	// GroupByReducerCountDistinct is an alias for GROUPBY reducer COUNT_DISTINCT
	GroupByReducerCountDistinct = GroupByReducers("COUNT_DISTINCT")

	// GroupByReducerCountDistinctish is an alias for GROUPBY reducer COUNT_DISTINCTISH
	GroupByReducerCountDistinctish = GroupByReducers("COUNT_DISTINCTISH")

	// GroupByReducerSum is an alias for GROUPBY reducer SUM
	GroupByReducerSum = GroupByReducers("SUM")

	// GroupByReducerMin is an alias for GROUPBY reducer MIN
	GroupByReducerMin = GroupByReducers("MIN")

	// GroupByReducerMax is an alias for GROUPBY reducer MAX
	GroupByReducerMax = GroupByReducers("MAX")

	// GroupByReducerAvg is an alias for GROUPBY reducer AVG
	GroupByReducerAvg = GroupByReducers("AVG")

	// GroupByReducerStdDev is an alias for GROUPBY reducer STDDEV
	GroupByReducerStdDev = GroupByReducers("STDDEV")

	// GroupByReducerQuantile is an alias for GROUPBY reducer QUANTILE
	GroupByReducerQuantile = GroupByReducers("QUANTILE")

	// GroupByReducerToList is an alias for GROUPBY reducer TOLIST
	GroupByReducerToList = GroupByReducers("TOLIST")

	// GroupByReducerFirstValue is an alias for GROUPBY reducer FIRST_VALUE
	GroupByReducerFirstValue = GroupByReducers("FIRST_VALUE")

	// GroupByReducerRandomSample is an alias for GROUPBY reducer RANDOM_SAMPLE
	GroupByReducerRandomSample = GroupByReducers("RANDOM_SAMPLE")
)

Variables

View Source
var DefaultIndexingOptions = IndexingOptions{
	Language:         "",
	NoSave:           false,
	Replace:          false,
	Partial:          false,
	ReplaceCondition: "",
}

DefaultIndexingOptions are the default options for document indexing

View Source
var DefaultOptions = Options{
	NoSave:            false,
	NoFieldFlags:      false,
	NoFrequencies:     false,
	NoOffsetVectors:   false,
	Stopwords:         nil,
	Temporary:         false,
	TemporaryPeriod:   0,
	MaxTextFieldsFlag: false,
}

DefaultOptions represents the default options

View Source
var DefaultSuggestOptions = SuggestOptions{
	Num:          5,
	Fuzzy:        false,
	WithPayloads: false,
	WithScores:   false,
}

DefaultIndexingOptions are the default options for document indexing

Functions

func EscapeTextFileString added in v0.2.0

func EscapeTextFileString(value string) string

All punctuation marks and whitespaces (besides underscores) separate the document and queries into tokens. e.g. any character of `,.<>{}[]"':;!@#$%^&*()-+=~` will break the text into terms. So the text `foo-bar.baz...bag` will be tokenized into `[foo, bar, baz, bag]` Escaping separators in both queries and documents is done by prepending a backslash to any separator. e.g. the text `hello\-world hello-world` will be tokenized as `[hello-world, hello, world]`. **NOTE** that in most languages you will need an extra backslash when formatting the document or query, to signify an actual backslash, so the actual text in redis-cli for example, will be entered as `hello\\-world`. Underscores (`_`) are not used as separators in either document or query. So the text `hello_world` will remain as is after tokenization.

func ProcessAggResponse deprecated added in v0.2.0

func ProcessAggResponse(res []interface{}) [][]string

Deprecated: Please use processAggReply() instead

func ProcessAggResponseSS added in v0.2.0

func ProcessAggResponseSS(res []interface{}) [][]string

func SerializeIndexingOptions added in v0.9.0

func SerializeIndexingOptions(opts IndexingOptions, args redis.Args) redis.Args

func SerializeSchema added in v0.9.0

func SerializeSchema(s *Schema, args redis.Args) (argsOut redis.Args, err error)

Types

type AggregateQuery added in v0.2.0

type AggregateQuery struct {
	Query         *Query
	AggregatePlan redis.Args
	Paging        *Paging
	Max           int
	WithSchema    bool
	Verbatim      bool
	WithCursor    bool
	Cursor        *Cursor
}

AggregateQuery

func NewAggregateQuery added in v0.2.0

func NewAggregateQuery() *AggregateQuery

func (*AggregateQuery) Apply added in v0.2.0

func (a *AggregateQuery) Apply(expression Projection) *AggregateQuery

Adds a APPLY clause to the aggregate plan

func (*AggregateQuery) CursorHasResults added in v0.2.0

func (a *AggregateQuery) CursorHasResults() (res bool)

func (*AggregateQuery) Filter added in v0.2.0

func (a *AggregateQuery) Filter(expression string) *AggregateQuery

Specify filters to filter the results using predicates relating to values in the result set.

func (*AggregateQuery) GroupBy added in v0.2.0

func (a *AggregateQuery) GroupBy(group GroupBy) *AggregateQuery

Adds a GROUPBY clause to the aggregate plan

func (*AggregateQuery) Limit added in v0.2.0

func (a *AggregateQuery) Limit(offset int, num int) *AggregateQuery

Sets the limit for the initial pool of results from the query.

func (*AggregateQuery) Load added in v0.9.0

func (a *AggregateQuery) Load(Properties []string) *AggregateQuery

Load document fields from the document HASH objects (if they are not in the sortables)

func (AggregateQuery) Serialize added in v0.2.0

func (q AggregateQuery) Serialize() redis.Args

func (*AggregateQuery) SetCursor added in v0.2.0

func (a *AggregateQuery) SetCursor(cursor *Cursor) *AggregateQuery

func (*AggregateQuery) SetMax added in v0.2.0

func (a *AggregateQuery) SetMax(value int) *AggregateQuery

func (*AggregateQuery) SetQuery added in v0.2.0

func (a *AggregateQuery) SetQuery(query *Query) *AggregateQuery

func (*AggregateQuery) SetVerbatim added in v0.2.0

func (a *AggregateQuery) SetVerbatim(value bool) *AggregateQuery

func (*AggregateQuery) SetWithSchema added in v0.2.0

func (a *AggregateQuery) SetWithSchema(value bool) *AggregateQuery

func (*AggregateQuery) SortBy added in v0.2.0

func (a *AggregateQuery) SortBy(SortByProperties []SortingKey) *AggregateQuery

Adds a SORTBY clause to the aggregate plan

type Autocompleter

type Autocompleter struct {
	// contains filtered or unexported fields
}

Autocompleter implements a redisearch auto-completer API

func NewAutocompleter

func NewAutocompleter(addr, name string) *Autocompleter

NewAutocompleter creates a new Autocompleter with the given host and key name

func NewAutocompleterFromPool added in v0.9.0

func NewAutocompleterFromPool(pool *redis.Pool, name string) *Autocompleter

NewAutocompleter creates a new Autocompleter with the given pool and key name

func (*Autocompleter) AddTerms

func (a *Autocompleter) AddTerms(terms ...Suggestion) error

AddTerms pushes new term suggestions to the index

func (*Autocompleter) Delete

func (a *Autocompleter) Delete() error

Delete deletes the Autocompleter key for this AC

func (*Autocompleter) DeleteTerms added in v0.9.0

func (a *Autocompleter) DeleteTerms(terms ...Suggestion) error

AddTerms pushes new term suggestions to the index

func (*Autocompleter) Length added in v0.9.0

func (a *Autocompleter) Length() (len int64, err error)

AddTerms pushes new term suggestions to the index

func (*Autocompleter) Serialize added in v0.9.0

func (a *Autocompleter) Serialize(prefix string, opts SuggestOptions) (redis.Args, int)

func (*Autocompleter) Suggest deprecated

func (a *Autocompleter) Suggest(prefix string, num int, fuzzy bool) (ret []Suggestion, err error)

Suggest gets completion suggestions from the Autocompleter dictionary to the given prefix. If fuzzy is set, we also complete for prefixes that are in 1 Levenshten distance from the given prefix

Deprecated: Please use SuggestOpts() instead

func (*Autocompleter) SuggestOpts

func (a *Autocompleter) SuggestOpts(prefix string, opts SuggestOptions) (ret []Suggestion, err error)

SuggestOpts gets completion suggestions from the Autocompleter dictionary to the given prefix. SuggestOptions are passed allowing you specify if the returned values contain a payload, and scores. If SuggestOptions.Fuzzy is set, we also complete for prefixes that are in 1 Levenshtein distance from the given prefix

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is an interface to redisearch's redis commands

func NewClient

func NewClient(addr, name string) *Client

NewClient creates a new client connecting to the redis host, and using the given name as key prefix. Addr can be a single host:port pair, or a comma separated list of host:port,host:port... In the case of multiple hosts we create a multi-pool and select connections at random

Example

exemplifies the NewClient function

package main

import (
	"fmt"
	"log"
	"time"

	"github.com/RediSearch/redisearch-go/redisearch"
)

func main() {
	// Create a client. By default a client is schemaless
	// unless a schema is provided when creating the index
	c := redisearch.NewClient("localhost:6379", "myIndex")

	// Create a schema
	sc := redisearch.NewSchema(redisearch.DefaultOptions).
		AddField(redisearch.NewTextField("body")).
		AddField(redisearch.NewTextFieldOptions("title", redisearch.TextFieldOptions{Weight: 5.0, Sortable: true})).
		AddField(redisearch.NewNumericField("date"))

	// Drop an existing index. If the index does not exist an error is returned
	c.Drop()

	// Create the index with the given schema
	if err := c.CreateIndex(sc); err != nil {
		log.Fatal(err)
	}

	// Create a document with an id and given score
	doc := redisearch.NewDocument("ExampleNewClient:doc1", 1.0)
	doc.Set("title", "Hello world").
		Set("body", "foo bar").
		Set("date", time.Now().Unix())

	// Index the document. The API accepts multiple documents at a time
	if err := c.Index([]redisearch.Document{doc}...); err != nil {
		log.Fatal(err)
	}

	// Wait for all documents to be indexed
	info, _ := c.Info()
	for info.IsIndexing {
		time.Sleep(time.Second)
		info, _ = c.Info()
	}

	// Searching with limit and sorting
	docs, total, err := c.Search(redisearch.NewQuery("hello world").
		Limit(0, 2).
		SetReturnFields("title"))

	fmt.Println(docs[0].Id, docs[0].Properties["title"], total, err)
	
Output:

func NewClientFromPool added in v1.0.0

func NewClientFromPool(pool *redis.Pool, name string) *Client

NewClientFromPool creates a new Client with the given pool and index name

Example

exemplifies the NewClientFromPool function

package main

import (
	"fmt"
	"log"
	"time"

	"github.com/RediSearch/redisearch-go/redisearch"
	"github.com/gomodule/redigo/redis"
)

func main() {
	host := "localhost:6379"
	password := ""
	pool := &redis.Pool{Dial: func() (redis.Conn, error) {
		return redis.Dial("tcp", host, redis.DialPassword(password))
	}}
	c := redisearch.NewClientFromPool(pool, "search-client-1")

	// Create a schema
	sc := redisearch.NewSchema(redisearch.DefaultOptions).
		AddField(redisearch.NewTextField("body")).
		AddField(redisearch.NewTextFieldOptions("title", redisearch.TextFieldOptions{Weight: 5.0, Sortable: true})).
		AddField(redisearch.NewNumericField("date"))

	// Drop an existing index. If the index does not exist an error is returned
	c.Drop()

	// Create the index with the given schema
	if err := c.CreateIndex(sc); err != nil {
		log.Fatal(err)
	}

	// Create a document with an id and given score
	doc := redisearch.NewDocument("ExampleNewClientFromPool:doc2", 1.0)
	doc.Set("title", "Hello world").
		Set("body", "foo bar").
		Set("date", time.Now().Unix())

	// Index the document. The API accepts multiple documents at a time
	if err := c.Index([]redisearch.Document{doc}...); err != nil {
		log.Fatal(err)
	}

	// Searching with limit and sorting
	docs, total, err := c.Search(redisearch.NewQuery("hello world").
		Limit(0, 2).
		SetReturnFields("title"))

	fmt.Println(docs[0].Id, docs[0].Properties["title"], total, err)
	
Output:

Example (Ssl)

Example of how to establish an SSL connection from your app to the RedisAI Server

package main

import (
	"crypto/tls"
	"crypto/x509"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"time"

	"github.com/RediSearch/redisearch-go/redisearch"
	"github.com/gomodule/redigo/redis"
)

func main() {
	// Consider the following helper methods that provide us with the connection details (host and password)
	// and the paths for:
	//     tls_cert - A a X.509 certificate to use for authenticating the  server to connected clients, masters or cluster peers. The file should be PEM formatted
	//     tls_key - A a X.509 private key to use for authenticating the  server to connected clients, masters or cluster peers. The file should be PEM formatted
	//	   tls_cacert - A PEM encoded CA's certificate file
	host, password := getConnectionDetails()
	tlsready, tls_cert, tls_key, tls_cacert := getTLSdetails()

	// Skip if we dont have all files to properly connect
	if tlsready == false {
		return
	}

	// Load client cert
	cert, err := tls.LoadX509KeyPair(tls_cert, tls_key)
	if err != nil {
		log.Fatal(err)
	}

	// Load CA cert
	caCert, err := ioutil.ReadFile(tls_cacert)
	if err != nil {
		log.Fatal(err)
	}
	caCertPool := x509.NewCertPool()
	caCertPool.AppendCertsFromPEM(caCert)

	clientTLSConfig := &tls.Config{
		Certificates: []tls.Certificate{cert},
		RootCAs:      caCertPool,
	}

	// InsecureSkipVerify controls whether a client verifies the
	// server's certificate chain and host name.
	// If InsecureSkipVerify is true, TLS accepts any certificate
	// presented by the server and any host name in that certificate.
	// In this mode, TLS is susceptible to man-in-the-middle attacks.
	// This should be used only for testing.
	clientTLSConfig.InsecureSkipVerify = true

	pool := &redis.Pool{Dial: func() (redis.Conn, error) {
		return redis.Dial("tcp", host,
			redis.DialPassword(password),
			redis.DialTLSConfig(clientTLSConfig),
			redis.DialUseTLS(true),
			redis.DialTLSSkipVerify(true),
		)
	}}

	c := redisearch.NewClientFromPool(pool, "search-client-1")

	// Create a schema
	sc := redisearch.NewSchema(redisearch.DefaultOptions).
		AddField(redisearch.NewTextField("body")).
		AddField(redisearch.NewTextFieldOptions("title", redisearch.TextFieldOptions{Weight: 5.0, Sortable: true})).
		AddField(redisearch.NewNumericField("date"))

	// Drop an existing index. If the index does not exist an error is returned
	c.Drop()

	// Create the index with the given schema
	if err := c.CreateIndex(sc); err != nil {
		log.Fatal(err)
	}

	// Create a document with an id and given score
	doc := redisearch.NewDocument("ExampleNewClientFromPool_ssl:doc3", 1.0)
	doc.Set("title", "Hello world").
		Set("body", "foo bar").
		Set("date", time.Now().Unix())

	// Index the document. The API accepts multiple documents at a time
	if err := c.Index([]redisearch.Document{doc}...); err != nil {
		log.Fatal(err)
	}

	// Searching with limit and sorting
	docs, total, err := c.Search(redisearch.NewQuery("hello world").
		Limit(0, 2).
		SetReturnFields("title"))

	fmt.Println(docs[0].Id, docs[0].Properties["title"], total, err)

	// Drop the existing index
	c.Drop()
}

func getConnectionDetails() (host string, password string) {
	value, exists := os.LookupEnv("REDISEARCH_TEST_HOST")
	host = "localhost:6379"
	password = ""
	valuePassword, existsPassword := os.LookupEnv("REDISEARCH_TEST_PASSWORD")
	if exists && value != "" {
		host = value
	}
	if existsPassword && valuePassword != "" {
		password = valuePassword
	}
	return
}

func getTLSdetails() (tlsready bool, tls_cert string, tls_key string, tls_cacert string) {
	tlsready = false
	value, exists := os.LookupEnv("TLS_CERT")
	if exists && value != "" {
		info, err := os.Stat(value)
		if os.IsNotExist(err) || info.IsDir() {
			return
		}
		tls_cert = value
	} else {
		return
	}
	value, exists = os.LookupEnv("TLS_KEY")
	if exists && value != "" {
		info, err := os.Stat(value)
		if os.IsNotExist(err) || info.IsDir() {
			return
		}
		tls_key = value
	} else {
		return
	}
	value, exists = os.LookupEnv("TLS_CACERT")
	if exists && value != "" {
		info, err := os.Stat(value)
		if os.IsNotExist(err) || info.IsDir() {
			return
		}
		tls_cacert = value
	} else {
		return
	}
	tlsready = true
	return
}
Output:

func (*Client) AddField added in v1.0.0

func (i *Client) AddField(f Field) error

AddField Adds a new field to the index.

func (*Client) AddHash added in v1.0.0

func (i *Client) AddHash(docId string, score float32, language string, replace bool) (string, error)

Adds a document to the index from an existing HASH key in Redis. Deprecated: This function is not longer supported on RediSearch 2.0 and above, use HSET instead See the example ExampleClient_CreateIndexWithIndexDefinition for a deeper understanding on how to move towards using hashes on your application

func (*Client) Aggregate added in v0.2.0

func (i *Client) Aggregate(q *AggregateQuery) (aggregateReply [][]string, total int, err error)

Aggregate

func (*Client) AliasAdd added in v0.9.0

func (i *Client) AliasAdd(name string) (err error)

Adds an alias to an index.

func (*Client) AliasDel added in v0.9.0

func (i *Client) AliasDel(name string) (err error)

Deletes an alias to an index.

func (*Client) AliasUpdate added in v0.9.0

func (i *Client) AliasUpdate(name string) (err error)

Deletes an alias to an index.

func (*Client) CreateIndex

func (i *Client) CreateIndex(schema *Schema) (err error)

CreateIndex configures the index and creates it on redis

func (*Client) CreateIndexWithIndexDefinition added in v1.1.0

func (i *Client) CreateIndexWithIndexDefinition(schema *Schema, definition *IndexDefinition) (err error)

CreateIndexWithIndexDefinition configures the index and creates it on redis IndexDefinition is used to define a index definition for automatic indexing on Hash update

Example

RediSearch 2.0, marks the re-architecture of the way indices are kept in sync with the data. Instead of having to write data through the index (using the FT.ADD command), RediSearch will now follow the data written in hashes and automatically index it. The following example illustrates how to achieve it with the go client

package main

import (
	"fmt"
	"time"

	"github.com/RediSearch/redisearch-go/redisearch"
	"github.com/gomodule/redigo/redis"
)

func main() {
	host := "localhost:6379"
	password := ""
	pool := &redis.Pool{Dial: func() (redis.Conn, error) {
		return redis.Dial("tcp", host, redis.DialPassword(password))
	}}
	c := redisearch.NewClientFromPool(pool, "products-from-hashes")

	// Create a schema
	schema := redisearch.NewSchema(redisearch.DefaultOptions).
		AddField(redisearch.NewTextFieldOptions("name", redisearch.TextFieldOptions{Sortable: true})).
		AddField(redisearch.NewTextFieldOptions("description", redisearch.TextFieldOptions{Weight: 5.0, Sortable: true})).
		AddField(redisearch.NewNumericField("price"))

	// IndexDefinition is available for RediSearch 2.0+
	// Create a index definition for automatic indexing on Hash updates.
	// In this example we will only index keys started by product:
	indexDefinition := redisearch.NewIndexDefinition().AddPrefix("product:")

	// Add the Index Definition
	c.CreateIndexWithIndexDefinition(schema, indexDefinition)

	// Get a vanilla connection and create 100 hashes
	vanillaConnection := pool.Get()
	for productNumber := 0; productNumber < 100; productNumber++ {
		vanillaConnection.Do("HSET", fmt.Sprintf("product:%d", productNumber), "name", fmt.Sprintf("product name %d", productNumber), "description", "product description", "price", 10.99)
	}

	// Wait for all documents to be indexed
	info, _ := c.Info()
	for info.IsIndexing {
		time.Sleep(time.Second)
		info, _ = c.Info()
	}

	_, total, _ := c.Search(redisearch.NewQuery("description"))

	fmt.Printf("Total documents containing \"description\": %d.\n", total)
}
Output:

Example (Phonetic)

exemplifies the CreateIndex function with phonetic matching on it in searches by default

package main

import (
	"fmt"
	"github.com/gomodule/redigo/redis"
	"time"

	"github.com/RediSearch/redisearch-go/redisearch"
)

func main() {
	// Create a client
	host := "localhost:6379"
	password := ""
	pool := &redis.Pool{Dial: func() (redis.Conn, error) {
		return redis.Dial("tcp", host, redis.DialPassword(password))
	}}
	c := redisearch.NewClientFromPool(pool, "myPhoneticIndex")

	// Create a schema
	schema := redisearch.NewSchema(redisearch.DefaultOptions).
		AddField(redisearch.NewTextFieldOptions("name", redisearch.TextFieldOptions{Sortable: true, PhoneticMatcher: redisearch.PhoneticDoubleMetaphoneEnglish})).
		AddField(redisearch.NewNumericField("age"))

	// IndexDefinition is available for RediSearch 2.0+
	// Create a index definition for automatic indexing on Hash updates.
	// In this example we will only index keys started by product:
	indexDefinition := redisearch.NewIndexDefinition().AddPrefix("myPhoneticIndex:")

	// Add the Index Definition
	c.CreateIndexWithIndexDefinition(schema, indexDefinition)

	// Create docs with a name that has the same phonetic matcher
	vanillaConnection := pool.Get()
	vanillaConnection.Do("HSET", "myPhoneticIndex:doc1", "name", "Jon", "age", 25)
	// Create a second document with a name that has the same phonetic matcher
	vanillaConnection.Do("HSET", "myPhoneticIndex:doc2", "name", "John", "age", 20)
	// Create a third document with a name that does not have the same phonetic matcher
	vanillaConnection.Do("HSET", "myPhoneticIndex:doc3", "name", "Pieter", "age", 30)

	// Wait for all documents to be indexed
	info, _ := c.Info()
	for info.IsIndexing {
		time.Sleep(time.Second)
		info, _ = c.Info()
	}

	_, total, _ := c.Search(redisearch.NewQuery("Jon").
		SetReturnFields("name"))

	// Verify that the we've received 2 documents ( Jon and John )
	fmt.Printf("Total docs replied %d\n", total)

}
Output:

Total docs replied 2

func (*Client) Delete added in v0.2.0

func (i *Client) Delete(docId string, deleteDocument bool) (err error)

Delete the document from the index, optionally delete the actual document WARNING: As of RediSearch 2.0 and above, FT.DEL always deletes the underlying document. Deprecated: This function is deprecated on RediSearch 2.0 and above, use DeleteDocument() instead

func (*Client) DeleteDocument added in v1.1.0

func (i *Client) DeleteDocument(docId string) (err error)

Delete the document from the index and also delete the HASH key in which the document is stored

func (*Client) DictAdd added in v0.9.0

func (i *Client) DictAdd(dictionaryName string, terms []string) (newTerms int, err error)

Adds terms to a dictionary.

func (*Client) DictDel added in v0.9.0

func (i *Client) DictDel(dictionaryName string, terms []string) (deletedTerms int, err error)

Deletes terms from a dictionary

func (*Client) DictDump added in v0.9.0

func (i *Client) DictDump(dictionaryName string) (terms []string, err error)

Dumps all terms in the given dictionary.

func (*Client) Drop

func (i *Client) Drop() error

Deletes the index and all the keys associated with it.

func (*Client) DropIndex added in v1.1.0

func (i *Client) DropIndex(deleteDocuments bool) error

Deletes the secondary index and optionally the associated hashes

Available since RediSearch 2.0.

By default, DropIndex() which is a wrapper for RediSearch FT.DROPINDEX does not delete the document hashes associated with the index. Setting the argument deleteDocuments to true deletes the hashes as well.

Example

The following example illustrates an index creation and deletion. By default, DropIndex() which is a wrapper for RediSearch FT.DROPINDEX does not delete the document hashes associated with the index. Setting the argument deleteDocuments to true deletes the hashes as well. Available since RediSearch 2.0

package main

import (
	"fmt"
	"log"
	"time"

	"github.com/RediSearch/redisearch-go/redisearch"
	"github.com/gomodule/redigo/redis"
)

func main() {

	host := "localhost:6379"
	password := ""
	pool := &redis.Pool{Dial: func() (redis.Conn, error) {
		return redis.Dial("tcp", host, redis.DialPassword(password))
	}}
	c := redisearch.NewClientFromPool(pool, "products-from-hashes")

	// Create a schema
	schema := redisearch.NewSchema(redisearch.DefaultOptions).
		AddField(redisearch.NewTextFieldOptions("name", redisearch.TextFieldOptions{Sortable: true})).
		AddField(redisearch.NewTextFieldOptions("description", redisearch.TextFieldOptions{Weight: 5.0, Sortable: true})).
		AddField(redisearch.NewNumericField("price"))

	// IndexDefinition is available for RediSearch 2.0+
	// Create a index definition for automatic indexing on Hash updates.
	// In this example we will only index keys started by product:
	indexDefinition := redisearch.NewIndexDefinition().AddPrefix("product:")

	// Add the Index Definition
	c.CreateIndexWithIndexDefinition(schema, indexDefinition)

	// Get a vanilla connection and create 100 hashes
	vanillaConnection := pool.Get()
	for productNumber := 0; productNumber < 100; productNumber++ {
		vanillaConnection.Do("HSET", fmt.Sprintf("product:%d", productNumber), "name", fmt.Sprintf("product name %d", productNumber), "description", "product description", "price", 10.99)
	}

	// Wait for all documents to be indexed
	info, _ := c.Info()
	for info.IsIndexing {
		time.Sleep(time.Second)
		info, _ = c.Info()
	}

	// Delete Index and Documents
	err := c.DropIndex(true)
	if err != nil {
		log.Fatal(err)
	}

}
Output:

func (*Client) Explain

func (i *Client) Explain(q *Query) (string, error)

Explain Return a textual string explaining the query

func (*Client) Get added in v0.9.0

func (i *Client) Get(docId string) (doc *Document, err error)

Get - Returns the full contents of a document

func (*Client) GetConfig added in v1.0.0

func (i *Client) GetConfig(option string) (map[string]string, error)

Get runtime configuration option value

func (*Client) GetTagVals added in v1.0.0

func (i *Client) GetTagVals(index string, filedName string) ([]string, error)

Get the distinct tags indexed in a Tag field

func (*Client) Index

func (i *Client) Index(docs ...Document) error

Index indexes a list of documents with the default options

func (*Client) IndexOptions

func (i *Client) IndexOptions(opts IndexingOptions, docs ...Document) error

IndexOptions indexes multiple documents on the index, with optional Options passed to options

func (*Client) Info

func (i *Client) Info() (*IndexInfo, error)

Info - Get information about the index. This can also be used to check if the index exists

func (*Client) List added in v1.1.1

func (i *Client) List() ([]string, error)

Returns a list of all existing indexes.

func (*Client) MultiGet added in v0.9.0

func (i *Client) MultiGet(documentIds []string) (docs []*Document, err error)

MultiGet - Returns the full contents of multiple documents. Returns an array with exactly the same number of elements as the number of keys sent to the command. Each element in it is either an Document or nil if it was not found.

func (*Client) Search

func (i *Client) Search(q *Query) (docs []Document, total int, err error)

Search searches the index for the given query, and returns documents, the total number of results, or an error if something went wrong

Example

The following example illustrates geospatial search using RediSearch. This examples maps to the Redis vanilla example showcased on https://redis.io/commands/georadius#examples. We'll start by adding two docs ( one for each city ) and then do a georadius search based on a starting point and 2 distinct radius: 1)- First query with 100KM radius centered at long,lat 15,37 that should only output the city named "Catania"; 2)- Second query with 200KM radius centered at long,lat 15,37 that should output the cities named "Palermo" and "Catania";

package main

import (
	"fmt"
	"log"

	"github.com/RediSearch/redisearch-go/redisearch"
)

func main() {
	// Create a client. By default a client is schemaless
	// unless a schema is provided when creating the index
	c := redisearch.NewClient("localhost:6379", "cityIndex")

	// Create a schema
	sc := redisearch.NewSchema(redisearch.DefaultOptions).
		AddField(redisearch.NewTextField("city")).
		AddField(redisearch.NewGeoField("location"))

	// Drop an existing index. If the index does not exist an error is returned
	c.Drop()

	// Create the index with the given schema
	if err := c.CreateIndex(sc); err != nil {
		log.Fatal(err)
	}

	// Create the city docs
	// Note While Specifying location you should specify in following order -> longitude,latitude
	// Same look and feel as GEOADD https://redis.io/commands/geoadd
	// This example maps to https://redis.io/commands/geoadd#examples
	docPalermo := redisearch.NewDocument("doc:Palermo", 1.0)
	docPalermo.Set("name", "Palermo").
		Set("location", "13.361389,38.115556")

	docCatania := redisearch.NewDocument("doc:Catania", 1.0)
	docCatania.Set("name", "Catania").
		Set("location", "15.087269,37.502669")

	// Index the documents. The API accepts multiple documents at a time
	if err := c.IndexOptions(redisearch.DefaultIndexingOptions, docPalermo, docCatania); err != nil {
		log.Fatal(err)
	}

	// Searching for 100KM radius should only output Catania
	docs, _, _ := c.Search(redisearch.NewQuery("*").AddFilter(
		redisearch.Filter{
			Field: "location",
			Options: redisearch.GeoFilterOptions{
				Lon:    15,
				Lat:    37,
				Radius: 100,
				Unit:   redisearch.KILOMETERS,
			},
		},
	).Limit(0, 2))

	fmt.Println("100KM Radius search from longitude 15 latitude 37")
	fmt.Println(docs[0])

	// Searching for 200KM radius should output Catania and Palermo
	docs, _, _ = c.Search(redisearch.NewQuery("*").AddFilter(
		redisearch.Filter{
			Field: "location",
			Options: redisearch.GeoFilterOptions{
				Lon:    15,
				Lat:    37,
				Radius: 200,
				Unit:   redisearch.KILOMETERS,
			},
		},
	).Limit(0, 2).SetSortBy("location", true))
	fmt.Println("200KM Radius search from longitude 15 latitude 37")
	fmt.Println(docs[0])
	fmt.Println(docs[1])

}
Output:

100KM Radius search from longitude 15 latitude 37
{doc:Catania 1 [] map[location:15.087269,37.502669 name:Catania]}
200KM Radius search from longitude 15 latitude 37
{doc:Palermo 1 [] map[location:13.361389,38.115556 name:Palermo]}
{doc:Catania 1 [] map[location:15.087269,37.502669 name:Catania]}

func (*Client) SetConfig added in v1.0.0

func (i *Client) SetConfig(option string, value string) (string, error)

Set runtime configuration option

func (*Client) SpellCheck added in v0.2.0

func (i *Client) SpellCheck(q *Query, s *SpellCheckOptions) (suggs []MisspelledTerm, total int, err error)

SpellCheck performs spelling correction on a query, returning suggestions for misspelled terms, the total number of results, or an error if something went wrong

func (*Client) SynAdd added in v1.0.0

func (i *Client) SynAdd(indexName string, terms []string) (int64, error)

Adds a synonym group. Deprecated: This function is not longer supported on RediSearch 2.0 and above, use SynUpdate instead

func (*Client) SynDump added in v1.0.0

func (i *Client) SynDump(indexName string) (map[string][]int64, error)

Dumps the contents of a synonym group.

func (*Client) SynUpdate added in v1.0.0

func (i *Client) SynUpdate(indexName string, synonymGroupId int64, terms []string) (string, error)

Updates a synonym group, with additional terms.

type ConnPool

type ConnPool interface {
	Get() redis.Conn
	Close() error
}

type Cursor added in v0.2.0

type Cursor struct {
	Id      int
	Count   int
	MaxIdle int
}

Cursor

func NewCursor added in v0.2.0

func NewCursor() *Cursor

func (Cursor) Serialize added in v0.2.0

func (c Cursor) Serialize() redis.Args

func (*Cursor) SetCount added in v0.2.0

func (c *Cursor) SetCount(count int) *Cursor

func (*Cursor) SetId added in v0.2.0

func (c *Cursor) SetId(id int) *Cursor

func (*Cursor) SetMaxIdle added in v0.2.0

func (c *Cursor) SetMaxIdle(maxIdle int) *Cursor

type Document

type Document struct {
	Id         string
	Score      float32
	Payload    []byte
	Properties map[string]interface{}
}

Document represents a single document to be indexed or returned from a query. Besides a score and id, the Properties are completely arbitrary

func NewDocument

func NewDocument(id string, score float32) Document

NewDocument creates a document with the specific id and score

func (*Document) EstimateSize

func (d *Document) EstimateSize() (sz int)

func (Document) Set

func (d Document) Set(name string, value interface{}) Document

Set sets a property and its value in the document

func (*Document) SetPayload

func (d *Document) SetPayload(payload []byte)

SetPayload Sets the document payload

type DocumentList

type DocumentList []Document

DocumentList is used to sort documents by descending score

func (DocumentList) Len

func (l DocumentList) Len() int

func (DocumentList) Less

func (l DocumentList) Less(i, j int) bool

func (DocumentList) Sort

func (l DocumentList) Sort()

Sort the DocumentList

func (DocumentList) Swap

func (l DocumentList) Swap(i, j int)

type Field

type Field struct {
	Name     string
	Type     FieldType
	Sortable bool
	Options  interface{}
}

Field represents a single field's Schema

func NewGeoField added in v1.0.0

func NewGeoField(name string) Field

NewGeoField creates a new geo field with the given name

func NewGeoFieldOptions added in v1.0.0

func NewGeoFieldOptions(name string, options GeoFieldOptions) Field

NewGeoFieldOptions creates a new geo field with the given name and additional options

func NewNumericField

func NewNumericField(name string) Field

NewNumericField creates a new numeric field with the given name

func NewNumericFieldOptions

func NewNumericFieldOptions(name string, options NumericFieldOptions) Field

NewNumericFieldOptions defines a numeric field with additional options

func NewSortableNumericField

func NewSortableNumericField(name string) Field

NewSortableNumericField creates a new numeric field with the given name and a sortable flag

func NewSortableTextField

func NewSortableTextField(name string, weight float32) Field

NewSortableTextField creates a text field with the sortable flag set

func NewTagField

func NewTagField(name string) Field

NewTagField creates a new text field with default options (separator: ,)

func NewTagFieldOptions

func NewTagFieldOptions(name string, opts TagFieldOptions) Field

NewTagFieldOptions creates a new tag field with the given options

func NewTextField

func NewTextField(name string) Field

NewTextField creates a new text field with the given weight

func NewTextFieldOptions

func NewTextFieldOptions(name string, opts TextFieldOptions) Field

NewTextFieldOptions creates a new text field with given options (weight/sortable)

type FieldType

type FieldType int

FieldType is an enumeration of field/property types

const (
	// TextField full-text field
	TextField FieldType = iota

	// NumericField numeric range field
	NumericField

	// GeoField geo-indexed point field
	GeoField

	// TagField is a field used for compact indexing of comma separated values
	TagField
)

Field Types

type Filter added in v1.0.0

type Filter struct {
	Field   string
	Options interface{}
}

Common filter

type Flag

type Flag uint64

Flag is a type for query flags

const (
	// Treat the terms verbatim and do not perform expansion
	QueryVerbatim Flag = 0x1

	// Do not load any content from the documents, return just IDs
	QueryNoContent Flag = 0x2

	// Fetch document scores as well as IDs and fields
	QueryWithScores Flag = 0x4

	// The query terms must appear in order in the document
	QueryInOrder Flag = 0x08

	// Fetch document payloads as well as fields. See documentation for payloads on redisearch.io
	QueryWithPayloads Flag = 0x10

	DefaultOffset = 0
	DefaultNum    = 10
)

Query Flags

type GeoFieldOptions added in v1.0.0

type GeoFieldOptions struct {
	NoIndex bool
}

GeoFieldOptions Options for geo fields

type GeoFilterOptions added in v1.0.0

type GeoFilterOptions struct {
	Lon    float64
	Lat    float64
	Radius float64
	Unit   Unit
}

FilterExpression the results to a given radius from lon and lat. Radius is given as a number and units

type GroupBy added in v0.2.0

type GroupBy struct {
	Fields   []string
	Reducers []Reducer
	Paging   *Paging
}

GroupBy

func NewGroupBy added in v0.2.0

func NewGroupBy() *GroupBy

func (*GroupBy) AddFields added in v0.2.0

func (g *GroupBy) AddFields(fields interface{}) *GroupBy

func (*GroupBy) Limit added in v0.2.0

func (g *GroupBy) Limit(offset int, num int) *GroupBy

func (*GroupBy) Reduce added in v0.2.0

func (g *GroupBy) Reduce(reducer Reducer) *GroupBy

func (GroupBy) Serialize added in v0.2.0

func (g GroupBy) Serialize() redis.Args

type GroupByReducers added in v0.2.0

type GroupByReducers string

GroupByReducers

type HighlightOptions

type HighlightOptions struct {
	Fields []string
	Tags   [2]string
}

HighlightOptions represents the options to higlight specific document fields. See http://redisearch.io/Highlight/

type IndexDefinition added in v1.1.0

type IndexDefinition struct {
	IndexOn          string
	Async            bool
	Prefix           []string
	FilterExpression string
	Language         string
	LanguageField    string
	Score            float64
	ScoreField       string
	PayloadField     string
}

IndexDefinition is used to define a index definition for automatic indexing on Hash update This is only valid for >= RediSearch 2.0

func NewIndexDefinition added in v1.1.0

func NewIndexDefinition() *IndexDefinition

This is only valid for >= RediSearch 2.0

func (*IndexDefinition) AddPrefix added in v1.1.0

func (defintion *IndexDefinition) AddPrefix(prefix string) (outDef *IndexDefinition)

This is only valid for >= RediSearch 2.0

func (*IndexDefinition) Serialize added in v1.1.0

func (defintion *IndexDefinition) Serialize(args redis.Args) redis.Args

This is only valid for >= RediSearch 2.0

func (*IndexDefinition) SetAsync added in v1.1.0

func (defintion *IndexDefinition) SetAsync(value bool) (outDef *IndexDefinition)

This is only valid for >= RediSearch 2.0

func (*IndexDefinition) SetFilterExpression added in v1.1.0

func (defintion *IndexDefinition) SetFilterExpression(value string) (outDef *IndexDefinition)

func (*IndexDefinition) SetLanguage added in v1.1.0

func (defintion *IndexDefinition) SetLanguage(value string) (outDef *IndexDefinition)

This is only valid for >= RediSearch 2.0

func (*IndexDefinition) SetLanguageField added in v1.1.0

func (defintion *IndexDefinition) SetLanguageField(value string) (outDef *IndexDefinition)

This is only valid for >= RediSearch 2.0

func (*IndexDefinition) SetPayloadField added in v1.1.0

func (defintion *IndexDefinition) SetPayloadField(value string) (outDef *IndexDefinition)

This is only valid for >= RediSearch 2.0

func (*IndexDefinition) SetScore added in v1.1.0

func (defintion *IndexDefinition) SetScore(value float64) (outDef *IndexDefinition)

This is only valid for >= RediSearch 2.0

func (*IndexDefinition) SetScoreField added in v1.1.0

func (defintion *IndexDefinition) SetScoreField(value string) (outDef *IndexDefinition)

This is only valid for >= RediSearch 2.0

type IndexInfo

type IndexInfo struct {
	Schema               Schema
	Name                 string  `redis:"index_name"`
	DocCount             uint64  `redis:"num_docs"`
	RecordCount          uint64  `redis:"num_records"`
	TermCount            uint64  `redis:"num_terms"`
	MaxDocID             uint64  `redis:"max_doc_id"`
	InvertedIndexSizeMB  float64 `redis:"inverted_sz_mb"`
	OffsetVectorSizeMB   float64 `redis:"offset_vector_sz_mb"`
	DocTableSizeMB       float64 `redis:"doc_table_size_mb"`
	KeyTableSizeMB       float64 `redis:"key_table_size_mb"`
	RecordsPerDocAvg     float64 `redis:"records_per_doc_avg"`
	BytesPerRecordAvg    float64 `redis:"bytes_per_record_avg"`
	OffsetsPerTermAvg    float64 `redis:"offsets_per_term_avg"`
	OffsetBitsPerTermAvg float64 `redis:"offset_bits_per_record_avg"`
	IsIndexing           bool    `redis:"indexing"`
	PercentIndexed       float64 `redis:"percent_indexed"`
	HashIndexingFailures uint64  `redis:"hash_indexing_failures"`
}

IndexInfo - Structure showing information about an existing index

type IndexingOptions

type IndexingOptions struct {

	// If set, we use a stemmer for the supplied language during indexing. If set to "", we Default to English.
	Language string

	// If set to true, we will not save the actual document in the database and only index it.
	// As of RediSearch 2.0 and above NOSAVE is no longer supported, and will have no effect
	NoSave bool

	//  If set, we will do an UPSERT style insertion - and delete an older version of the document if it exists.
	Replace bool

	// (only applicable with Replace): If set, you do not have to specify all fields for reindexing.
	Partial bool

	// Applicable only in conjunction with Replace and optionally Partial
	// Update the document only if a boolean expression applies to the document before the update
	ReplaceCondition string
}

IndexingOptions represent the options for indexing a single document

type MisspelledSuggestion added in v0.2.0

type MisspelledSuggestion struct {
	Suggestion string
	Score      float32
}

MisspelledSuggestion is a single suggestion from the spelling corrections

func NewMisspelledSuggestion added in v0.2.0

func NewMisspelledSuggestion(term string, score float32) MisspelledSuggestion

NewMisspelledSuggestion creates a MisspelledSuggestion with the specific term and score

type MisspelledTerm added in v0.2.0

type MisspelledTerm struct {
	Term string
	// MisspelledSuggestionList is a sortable list of suggestions returned from an engine
	MisspelledSuggestionList []MisspelledSuggestion
}

MisspelledTerm contains the misspelled term and a sortable list of suggestions returned from an engine

func NewMisspelledTerm added in v0.2.0

func NewMisspelledTerm(term string) MisspelledTerm

func (MisspelledTerm) Len added in v0.2.0

func (l MisspelledTerm) Len() int

func (MisspelledTerm) Less added in v0.2.0

func (l MisspelledTerm) Less(i, j int) bool

func (MisspelledTerm) Sort added in v0.2.0

func (l MisspelledTerm) Sort()

Sort the SuggestionList

func (MisspelledTerm) Swap added in v0.2.0

func (l MisspelledTerm) Swap(i, j int)

type MultiError

type MultiError []error

MultiError Represents one or more errors

func NewMultiError

func NewMultiError(len int) MultiError

NewMultiError initializes a multierror with the given len, and all sub-errors set to nil

func (MultiError) Error

func (e MultiError) Error() string

Error returns a string representation of the error, in this case it just chains all the sub errors if they are not nil

type MultiHostPool

type MultiHostPool struct {
	sync.Mutex
	// contains filtered or unexported fields
}

func NewMultiHostPool

func NewMultiHostPool(hosts []string) *MultiHostPool

func (*MultiHostPool) Close added in v1.0.0

func (p *MultiHostPool) Close() (err error)

func (*MultiHostPool) Get

func (p *MultiHostPool) Get() redis.Conn

type NumericFieldOptions

type NumericFieldOptions struct {
	Sortable bool
	NoIndex  bool
}

NumericFieldOptions Options for numeric fields

type NumericFilterOptions added in v1.0.0

type NumericFilterOptions struct {
	Min          float64
	ExclusiveMin bool
	Max          float64
	ExclusiveMax bool
}

Limit results to those having numeric values ranging between min and max. min and max follow ZRANGE syntax, and can be -inf, +inf

type Operator

type Operator string
const (
	Eq Operator = "="

	Gt  Operator = ">"
	Gte Operator = ">="

	Lt  Operator = "<"
	Lte Operator = "<="

	Between          Operator = "BETWEEN"
	BetweenInclusive Operator = "BETWEEEN_EXCLUSIVE"
)

type Options

type Options struct {

	// If set, we will not save the documents contents, just index them, for fetching ids only.
	NoSave bool

	// If set, we avoid saving field bits for each term.
	// This saves memory, but does not allow filtering by specific fields.
	// This is an option that is applied and index level.
	NoFieldFlags bool

	// If set, we avoid saving the term frequencies in the index.
	// This saves memory but does not allow sorting based on the frequencies of a given term within the document.
	// This is an option that is applied and index level.
	NoFrequencies bool

	// If set, , we avoid saving the term offsets for documents.
	// This saves memory but does not allow exact searches or highlighting. Implies NOHL
	// This is an option that is applied and index level.
	NoOffsetVectors bool

	// Set the index with a custom stop-words list, to be ignored during indexing and search time
	// This is an option that is applied and index level.
	// If the list is nil the default stop-words list is used.
	// See https://oss.redislabs.com/redisearch/Stopwords.html#default_stop-word_list
	Stopwords []string

	// If set to true, creates a lightweight temporary index which will expire after the specified period of inactivity.
	// The internal idle timer is reset whenever the index is searched or added to.
	// Because such indexes are lightweight, you can create thousands of such indexes without negative performance implications.
	Temporary       bool
	TemporaryPeriod int

	// For efficiency, RediSearch encodes indexes differently if they are created with less than 32 text fields.
	// If set to true This option forces RediSearch to encode indexes as if there were more than 32 text fields,
	// which allows you to add additional fields (beyond 32).
	MaxTextFieldsFlag bool
}

Options are flags passed to the the abstract Index call, which receives them as interface{}, allowing for implementation specific options

func NewOptions added in v1.0.1

func NewOptions() *Options

func (*Options) SetMaxTextFieldsFlag added in v1.1.0

func (options *Options) SetMaxTextFieldsFlag(flag bool) *Options

For efficiency, RediSearch encodes indexes differently if they are created with less than 32 text fields. If set to true, this flag forces RediSearch to encode indexes as if there were more than 32 text fields, which allows you to add additional fields (beyond 32).

func (*Options) SetStopWords added in v1.0.1

func (options *Options) SetStopWords(stopwords []string) *Options

Set the index with a custom stop-words list, to be ignored during indexing and search time This is an option that is applied and index level. If the list is nil the default stop-words list is used. See https://oss.redislabs.com/redisearch/Stopwords.html#default_stop-word_list

func (*Options) SetTemporary added in v1.0.1

func (options *Options) SetTemporary(temporary bool) *Options

If set to true, creates a lightweight temporary index which will expire after the specified period of inactivity. The internal idle timer is reset whenever the index is searched or added to. To enable the temporary index creation, use SetTemporaryPeriod(). This method should be preferably used for disabling the flag

func (*Options) SetTemporaryPeriod added in v1.0.1

func (options *Options) SetTemporaryPeriod(period int) *Options

If set to a positive integer, creates a lightweight temporary index which will expire after the specified period of inactivity (in seconds). The internal idle timer is reset whenever the index is searched or added to.

type Paging

type Paging struct {
	Offset int
	Num    int
}

Paging represents the offset paging of a search result

func NewPaging added in v0.2.0

func NewPaging(offset int, num int) *Paging

type PhoneticMatcherType added in v1.1.0

type PhoneticMatcherType string

PhoneticMatcherType is an enumeration of the phonetic algorithm and language used.

const (
	PhoneticDoubleMetaphoneEnglish    PhoneticMatcherType = "dm:en"
	PhoneticDoubleMetaphoneFrench     PhoneticMatcherType = "dm:fr"
	PhoneticDoubleMetaphonePortuguese PhoneticMatcherType = "dm:pt"
	PhoneticDoubleMetaphoneSpanish    PhoneticMatcherType = "dm:es"
)

Phonetic Matchers

type Predicate

type Predicate struct {
	Property string
	Operator Operator
	Value    []interface{}
}

func Equals

func Equals(property string, value interface{}) Predicate

func GreaterThan

func GreaterThan(property string, value interface{}) Predicate

func GreaterThanEquals

func GreaterThanEquals(property string, value interface{}) Predicate

func InRange

func InRange(property string, min, max interface{}, inclusive bool) Predicate

func LessThan

func LessThan(property string, value interface{}) Predicate

func LessThanEquals

func LessThanEquals(property string, value interface{}) Predicate

func NewPredicate

func NewPredicate(property string, operator Operator, values ...interface{}) Predicate

type Projection added in v0.2.0

type Projection struct {
	Expression string
	Alias      string
}

Projection

func NewProjection added in v0.2.0

func NewProjection(expression string, alias string) *Projection

func (Projection) Serialize added in v0.2.0

func (p Projection) Serialize() redis.Args

type Query

type Query struct {
	Raw string

	Paging Paging
	Flags  Flag
	Slop   *int

	Filters       []Filter
	InKeys        []string
	InFields      []string
	ReturnFields  []string
	Language      string
	Expander      string
	Scorer        string
	Payload       []byte
	SortBy        *SortingKey
	HighlightOpts *HighlightOptions
	SummarizeOpts *SummaryOptions
}

Query is a single search query and all its parameters and predicates

func NewQuery

func NewQuery(raw string) *Query

NewQuery creates a new query for a given index with the given search term. For currently the index parameter is ignored

func (*Query) AddFilter added in v1.0.0

func (q *Query) AddFilter(f Filter) *Query

AddFilter adds a filter to the query

func (*Query) Highlight

func (q *Query) Highlight(fields []string, openTag, closeTag string) *Query

Highlight sets highighting on given fields. Highlighting marks all the query terms with the given open and close tags (i.e. <b> and </b> for HTML)

func (*Query) Limit

func (q *Query) Limit(offset, num int) *Query

Limit sets the paging offset and limit for the query you can use LIMIT 0 0 to count the number of documents in the resultset without actually returning them

func (*Query) SetExpander

func (q *Query) SetExpander(exp string) *Query

SetExpander sets a custom user query expander to be used

func (*Query) SetFlags

func (q *Query) SetFlags(flags Flag) *Query

SetFlags sets the query's optional flags

func (*Query) SetInFields added in v1.0.1

func (q *Query) SetInFields(fields ...string) *Query

SetInFields sets the INFIELDS argument of the query - filter the results to ones appearing only in specific fields of the document

func (*Query) SetInKeys

func (q *Query) SetInKeys(keys ...string) *Query

SetInKeys sets the INKEYS argument of the query - limiting the search to a given set of IDs

func (*Query) SetLanguage

func (q *Query) SetLanguage(lang string) *Query

SetLanguage sets the query language, used by the stemmer to expand the query

func (*Query) SetPayload

func (q *Query) SetPayload(payload []byte) *Query

SetPayload sets a binary payload to the query, that can be used by custom scoring functions

func (*Query) SetReturnFields

func (q *Query) SetReturnFields(fields ...string) *Query

SetReturnFields sets the fields that should be returned from each result. By default we return everything

func (*Query) SetScorer

func (q *Query) SetScorer(scorer string) *Query

SetScorer sets an alternative scoring function to be used. The only pre-compiled supported one at the moment is DISMAX

func (*Query) SetSortBy

func (q *Query) SetSortBy(field string, ascending bool) *Query

SetSortBy sets the sorting key for the query

func (*Query) Summarize

func (q *Query) Summarize(fields ...string) *Query

Summarize sets summarization on the given list of fields. It will instruct the engine to extract the most relevant snippets from the fields and return them as the field content. This function works with the default values of the engine, and only sets the fields. There is a function that accepts all options - SummarizeOptions

func (*Query) SummarizeOptions

func (q *Query) SummarizeOptions(opts SummaryOptions) *Query

SummarizeOptions sets summarization on the given list of fields. It will instruct the engine to extract the most relevant snippets from the fields and return them as the field content.

This function accepts advanced settings for snippet length, separators and number of snippets

type Reducer added in v0.2.0

type Reducer struct {
	Name  GroupByReducers
	Alias string
	Args  []string
}

Reducer represents an index schema Schema, or how the index would treat documents sent to it.

func NewReducer added in v0.2.0

func NewReducer(name GroupByReducers, args []string) *Reducer

NewReducer creates a new Reducer object

func NewReducerAlias added in v0.2.0

func NewReducerAlias(name GroupByReducers, args []string, alias string) *Reducer

NewReducer creates a new Reducer object

func (Reducer) Serialize added in v0.2.0

func (r Reducer) Serialize() redis.Args

func (*Reducer) SetAlias added in v0.2.0

func (r *Reducer) SetAlias(a string) *Reducer

func (*Reducer) SetArgs added in v0.2.0

func (r *Reducer) SetArgs(args []string) *Reducer

func (*Reducer) SetName added in v0.2.0

func (r *Reducer) SetName(reducer GroupByReducers) *Reducer

type Schema

type Schema struct {
	Fields  []Field
	Options Options
}

Schema represents an index schema Schema, or how the index would treat documents sent to it.

func NewSchema

func NewSchema(opts Options) *Schema

NewSchema creates a new Schema object

func (*Schema) AddField

func (m *Schema) AddField(f Field) *Schema

AddField adds a field to the Schema object

type SingleHostPool

type SingleHostPool struct {
	*redis.Pool
}

func NewSingleHostPool

func NewSingleHostPool(host string) *SingleHostPool

type SortingKey

type SortingKey struct {
	Field     string
	Ascending bool
}

SortingKey represents the sorting option if the query needs to be sorted based on a sortable fields and not a ranking function. See http://redisearch.io/Sorting/

func NewSortingKeyDir added in v0.2.0

func NewSortingKeyDir(field string, ascending bool) *SortingKey

func (SortingKey) Serialize added in v0.2.0

func (s SortingKey) Serialize() redis.Args

type SpellCheckOptions added in v0.2.0

type SpellCheckOptions struct {
	Distance       int
	ExclusionDicts []string
	InclusionDicts []string
}

SpellCheckOptions are options which are passed when performing spelling correction on a query

func NewSpellCheckOptions added in v0.2.0

func NewSpellCheckOptions(distance int) *SpellCheckOptions

func NewSpellCheckOptionsDefaults added in v0.2.0

func NewSpellCheckOptionsDefaults() *SpellCheckOptions

func (*SpellCheckOptions) AddExclusionDict added in v0.2.0

func (s *SpellCheckOptions) AddExclusionDict(dictname string) *SpellCheckOptions

AddExclusionDict adds a custom dictionary named {dictname} to the exclusion list

func (*SpellCheckOptions) AddInclusionDict added in v0.2.0

func (s *SpellCheckOptions) AddInclusionDict(dictname string) *SpellCheckOptions

AddInclusionDict adds a custom dictionary named {dictname} to the inclusion list

func (*SpellCheckOptions) SetDistance added in v0.2.0

func (s *SpellCheckOptions) SetDistance(distance int) (*SpellCheckOptions, error)

SetDistance Sets the the maximal Levenshtein distance for spelling suggestions (default: 1, max: 4)

type SuggestOptions

type SuggestOptions struct {
	Num          int
	Fuzzy        bool
	WithPayloads bool
	WithScores   bool
}

SuggestOptions are options which are passed when recieving suggestions from the Autocompleter

type Suggestion

type Suggestion struct {
	Term    string
	Score   float64
	Payload string
	Incr    bool
}

Suggestion is a single suggestion being added or received from the Autocompleter

func ProcessSugGetVals added in v0.9.0

func ProcessSugGetVals(vals []string, inc int, WithScores, WithPayloads bool) (ret []Suggestion)

type SuggestionList

type SuggestionList []Suggestion

SuggestionList is a sortable list of suggestions returned from an engine

func (SuggestionList) Len

func (l SuggestionList) Len() int

func (SuggestionList) Less

func (l SuggestionList) Less(i, j int) bool

func (SuggestionList) Sort

func (l SuggestionList) Sort()

Sort the SuggestionList

func (SuggestionList) Swap

func (l SuggestionList) Swap(i, j int)

type SummaryOptions

type SummaryOptions struct {
	Fields       []string
	FragmentLen  int    // default 20
	NumFragments int    // default 3
	Separator    string // default "..."
}

SummaryOptions represents the configuration used to create field summaries. See http://redisearch.io/Highlight/

type TagFieldOptions

type TagFieldOptions struct {
	// Separator is the custom separator between tags. defaults to comma (,)
	Separator byte
	NoIndex   bool
	Sortable  bool
}

TagFieldOptions options for indexing tag fields

type TextFieldOptions

type TextFieldOptions struct {
	Weight          float32
	Sortable        bool
	NoStem          bool
	NoIndex         bool
	PhoneticMatcher PhoneticMatcherType
}

TextFieldOptions Options for text fields - weight and stemming enabled/disabled.

type Unit added in v1.0.0

type Unit string

units of Radius

const (
	KILOMETERS Unit = "km"
	METERS     Unit = "m"
	FEET       Unit = "ft"
	MILES      Unit = "mi"
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL