Documentation ¶
Index ¶
- Constants
- Variables
- func EscapeTextFileString(value string) string
- func ProcessAggResponse(res []interface{}) [][]stringdeprecated
- func ProcessAggResponseSS(res []interface{}) [][]string
- func SerializeIndexingOptions(opts IndexingOptions, args redis.Args) redis.Args
- func SerializeSchema(s *Schema, args redis.Args) (argsOut redis.Args, err error)
- type AggregateQuery
- func (a *AggregateQuery) Apply(expression Projection) *AggregateQuery
- func (a *AggregateQuery) CursorHasResults() (res bool)
- func (a *AggregateQuery) Filter(expression string) *AggregateQuery
- func (a *AggregateQuery) GroupBy(group GroupBy) *AggregateQuery
- func (a *AggregateQuery) Limit(offset int, num int) *AggregateQuery
- func (a *AggregateQuery) Load(Properties []string) *AggregateQuery
- func (q AggregateQuery) Serialize() redis.Args
- func (a *AggregateQuery) SetCursor(cursor *Cursor) *AggregateQuery
- func (a *AggregateQuery) SetMax(value int) *AggregateQuery
- func (a *AggregateQuery) SetQuery(query *Query) *AggregateQuery
- func (a *AggregateQuery) SetVerbatim(value bool) *AggregateQuery
- func (a *AggregateQuery) SetWithSchema(value bool) *AggregateQuery
- func (a *AggregateQuery) SortBy(SortByProperties []SortingKey) *AggregateQuery
- type Autocompleter
- func (a *Autocompleter) AddTerms(terms ...Suggestion) error
- func (a *Autocompleter) Delete() error
- func (a *Autocompleter) DeleteTerms(terms ...Suggestion) error
- func (a *Autocompleter) Length() (len int64, err error)
- func (a *Autocompleter) Serialize(prefix string, opts SuggestOptions) (redis.Args, int)
- func (a *Autocompleter) Suggest(prefix string, num int, fuzzy bool) (ret []Suggestion, err error)deprecated
- func (a *Autocompleter) SuggestOpts(prefix string, opts SuggestOptions) (ret []Suggestion, err error)
- type Client
- func (i *Client) AddField(f Field) error
- func (i *Client) AddHash(docId string, score float32, language string, replace bool) (string, error)
- func (i *Client) Aggregate(q *AggregateQuery) (aggregateReply [][]string, total int, err error)deprecated
- func (i *Client) AggregateQuery(q *AggregateQuery) (total int, aggregateReply []map[string]interface{}, err error)
- func (i *Client) AliasAdd(name string) (err error)
- func (i *Client) AliasDel(name string) (err error)
- func (i *Client) AliasUpdate(name string) (err error)
- func (i *Client) CreateIndex(schema *Schema) (err error)
- func (i *Client) CreateIndexWithIndexDefinition(schema *Schema, definition *IndexDefinition) (err error)
- func (i *Client) Delete(docId string, deleteDocument bool) (err error)
- func (i *Client) DeleteDocument(docId string) (err error)
- func (i *Client) DictAdd(dictionaryName string, terms []string) (newTerms int, err error)
- func (i *Client) DictDel(dictionaryName string, terms []string) (deletedTerms int, err error)
- func (i *Client) DictDump(dictionaryName string) (terms []string, err error)
- func (i *Client) Drop() error
- func (i *Client) DropIndex(deleteDocuments bool) error
- func (i *Client) Explain(q *Query) (string, error)
- func (i *Client) Get(docId string) (doc *Document, err error)
- func (i *Client) GetConfig(option string) (map[string]string, error)
- func (i *Client) GetTagVals(index string, filedName string) ([]string, error)
- func (i *Client) Index(docs ...Document) error
- func (i *Client) IndexOptions(opts IndexingOptions, docs ...Document) error
- func (i *Client) Info() (*IndexInfo, error)
- func (i *Client) List() ([]string, error)
- func (i *Client) MultiGet(documentIds []string) (docs []*Document, err error)
- func (i *Client) Search(q *Query) (docs []Document, total int, err error)
- func (i *Client) SetConfig(option string, value string) (string, error)
- func (i *Client) SpellCheck(q *Query, s *SpellCheckOptions) (suggs []MisspelledTerm, total int, err error)
- func (i *Client) SynAdd(indexName string, terms []string) (int64, error)
- func (i *Client) SynDump(indexName string) (map[string][]int64, error)
- func (i *Client) SynUpdate(indexName string, synonymGroupId int64, terms []string) (string, error)
- type ConnPool
- type Cursor
- type Document
- type DocumentList
- type Field
- func NewGeoField(name string) Field
- func NewGeoFieldOptions(name string, options GeoFieldOptions) Field
- func NewNumericField(name string) Field
- func NewNumericFieldOptions(name string, options NumericFieldOptions) Field
- func NewSortableNumericField(name string) Field
- func NewSortableTextField(name string, weight float32) Field
- func NewTagField(name string) Field
- func NewTagFieldOptions(name string, opts TagFieldOptions) Field
- func NewTextField(name string) Field
- func NewTextFieldOptions(name string, opts TextFieldOptions) Field
- func NewVectorFieldOptions(name string, options VectorFieldOptions) Field
- type FieldType
- type Filter
- type Flag
- type GeoFieldOptions
- type GeoFilterOptions
- type GroupBy
- type GroupByReducers
- type HighlightOptions
- type IndexDefinition
- func (defintion *IndexDefinition) AddPrefix(prefix string) (outDef *IndexDefinition)
- func (defintion *IndexDefinition) Serialize(args redis.Args) redis.Args
- func (defintion *IndexDefinition) SetAsync(value bool) (outDef *IndexDefinition)
- func (defintion *IndexDefinition) SetFilterExpression(value string) (outDef *IndexDefinition)
- func (defintion *IndexDefinition) SetIndexOn(value IndexType) (outDef *IndexDefinition)
- func (defintion *IndexDefinition) SetLanguage(value string) (outDef *IndexDefinition)
- func (defintion *IndexDefinition) SetLanguageField(value string) (outDef *IndexDefinition)
- func (defintion *IndexDefinition) SetPayloadField(value string) (outDef *IndexDefinition)
- func (defintion *IndexDefinition) SetScore(value float64) (outDef *IndexDefinition)
- func (defintion *IndexDefinition) SetScoreField(value string) (outDef *IndexDefinition)
- type IndexInfo
- type IndexType
- type IndexingOptions
- type MisspelledSuggestion
- type MisspelledTerm
- type MultiError
- type MultiHostPool
- type NumericFieldOptions
- type NumericFilterOptions
- type Operator
- type Options
- func (options *Options) SetMaxTextFieldsFlag(flag bool) *Options
- func (options *Options) SetNoHighlight(flag bool) *Options
- func (options *Options) SetSkipInitialScan(flag bool) *Options
- func (options *Options) SetStopWords(stopwords []string) *Options
- func (options *Options) SetTemporary(temporary bool) *Options
- func (options *Options) SetTemporaryPeriod(period int) *Options
- type Paging
- type PhoneticMatcherType
- type Predicate
- func Equals(property string, value interface{}) Predicate
- func GreaterThan(property string, value interface{}) Predicate
- func GreaterThanEquals(property string, value interface{}) Predicate
- func InRange(property string, min, max interface{}, inclusive bool) Predicate
- func LessThan(property string, value interface{}) Predicate
- func LessThanEquals(property string, value interface{}) Predicate
- func NewPredicate(property string, operator Operator, values ...interface{}) Predicate
- type Projection
- type Query
- func (q *Query) AddFilter(f Filter) *Query
- func (q *Query) AddParam(name string, value interface{}) *Query
- func (q *Query) AddReturnField(field string, asName string) *Query
- func (q *Query) AddReturnFields(fields ...string) *Query
- func (q *Query) Highlight(fields []string, openTag, closeTag string) *Query
- func (q *Query) Limit(offset, num int) *Query
- func (q *Query) SetDialect(dialect int) *Query
- func (q *Query) SetExpander(exp string) *Query
- func (q *Query) SetFlags(flags Flag) *Query
- func (q *Query) SetInFields(fields ...string) *Query
- func (q *Query) SetInKeys(keys ...string) *Query
- func (q *Query) SetLanguage(lang string) *Query
- func (q *Query) SetParams(params map[string]interface{}) *Query
- func (q *Query) SetPayload(payload []byte) *Query
- func (q *Query) SetReturnFields(fields ...string) *Query
- func (q *Query) SetScorer(scorer string) *Query
- func (q *Query) SetSortBy(field string, ascending bool) *Query
- func (q *Query) Summarize(fields ...string) *Query
- func (q *Query) SummarizeOptions(opts SummaryOptions) *Query
- type Reducer
- type Schema
- type SingleHostPool
- type SortingKey
- type SpellCheckOptions
- type SuggestOptions
- type Suggestion
- type SuggestionList
- type SummaryOptions
- type TagFieldOptions
- type TextFieldOptions
- type Unit
- type VectorFieldOptions
Examples ¶
Constants ¶
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") )
const ( Flat algorithm = "FLAT" HNSW algorithm = "HNSW" )
Supported algorithms for Vector field
Variables ¶
var DefaultIndexingOptions = IndexingOptions{ Language: "", NoSave: false, Replace: false, Partial: false, ReplaceCondition: "", }
DefaultIndexingOptions are the default options for document indexing
var DefaultOptions = Options{ NoSave: false, NoFieldFlags: false, NoFrequencies: false, NoOffsetVectors: false, Stopwords: nil, Temporary: false, TemporaryPeriod: 0, MaxTextFieldsFlag: false, NoHighlights: false, SkipInitialScan: false, }
DefaultOptions represents the default options
var DefaultSuggestOptions = SuggestOptions{ Num: 5, Fuzzy: false, WithPayloads: false, WithScores: false, }
DefaultIndexingOptions are the default options for document indexing
Functions ¶
func EscapeTextFileString ¶
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
func ProcessAggResponse(res []interface{}) [][]string
Deprecated: Please use processAggReply() instead
func ProcessAggResponseSS ¶
func ProcessAggResponseSS(res []interface{}) [][]string
func SerializeIndexingOptions ¶
func SerializeIndexingOptions(opts IndexingOptions, args redis.Args) redis.Args
Types ¶
type AggregateQuery ¶
type AggregateQuery struct { Query *Query AggregatePlan redis.Args Paging *Paging Max int WithSchema bool Verbatim bool WithCursor bool Cursor *Cursor }
AggregateQuery
func NewAggregateQuery ¶
func NewAggregateQuery() *AggregateQuery
func (*AggregateQuery) Apply ¶
func (a *AggregateQuery) Apply(expression Projection) *AggregateQuery
Apply a 1-to-1 transformation on some property
func (*AggregateQuery) CursorHasResults ¶
func (a *AggregateQuery) CursorHasResults() (res bool)
func (*AggregateQuery) Filter ¶
func (a *AggregateQuery) Filter(expression string) *AggregateQuery
Filter the results using predicate expressions relating to values in each result. They are is applied post-query and relate to the current state of the pipeline.
func (*AggregateQuery) GroupBy ¶
func (a *AggregateQuery) GroupBy(group GroupBy) *AggregateQuery
Adds a GROUPBY clause to the aggregate plan
func (*AggregateQuery) Limit ¶
func (a *AggregateQuery) Limit(offset int, num int) *AggregateQuery
Limit the number of results to return just num results starting at index offset (zero-based).
func (*AggregateQuery) Load ¶
func (a *AggregateQuery) Load(Properties []string) *AggregateQuery
Load document fields from the document HASH objects (if they are not in the sortables). Empty array will load all properties.
func (AggregateQuery) Serialize ¶
func (q AggregateQuery) Serialize() redis.Args
func (*AggregateQuery) SetCursor ¶
func (a *AggregateQuery) SetCursor(cursor *Cursor) *AggregateQuery
func (*AggregateQuery) SetMax ¶
func (a *AggregateQuery) SetMax(value int) *AggregateQuery
SetMax is used to optimized sorting, by sorting only for the n-largest elements
func (*AggregateQuery) SetQuery ¶
func (a *AggregateQuery) SetQuery(query *Query) *AggregateQuery
SetQuery sets the query to the AggregateQuery
func (*AggregateQuery) SetVerbatim ¶
func (a *AggregateQuery) SetVerbatim(value bool) *AggregateQuery
SetVerbatim - If set, we do not try to use stemming for query expansion but search the query terms verbatim.
func (*AggregateQuery) SetWithSchema ¶
func (a *AggregateQuery) SetWithSchema(value bool) *AggregateQuery
func (*AggregateQuery) SortBy ¶
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 ¶
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 ¶
func (a *Autocompleter) DeleteTerms(terms ...Suggestion) error
DeleteTerms deletes term suggestions from the index
func (*Autocompleter) Length ¶
func (a *Autocompleter) Length() (len int64, err error)
Length gets the size of the suggestion
func (*Autocompleter) Serialize ¶
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 ¶
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/v2/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 ¶
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/v2/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/v2/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) AddHash ¶
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) AggregateQuery ¶
func (i *Client) AggregateQuery(q *AggregateQuery) (total int, aggregateReply []map[string]interface{}, err error)
AggregateQuery replaces the Aggregate() function. The reply is slice of maps, with values of either string or []string.
func (*Client) AliasAdd ¶
AliasAdd adds an alias to an index. Indexes can have more than one alias, though an alias cannot refer to another alias.
func (*Client) AliasUpdate ¶
AliasUpdate differs from the AliasAdd in that it will remove the alias association with a previous index, if any. AliasAdd will fail, on the other hand, if the alias is already associated with another index.
func (*Client) CreateIndex ¶
CreateIndex configures the index and creates it on redis
func (*Client) CreateIndexWithIndexDefinition ¶
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/v2/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" "time" "github.com/gomodule/redigo/redis" "github.com/RediSearch/redisearch-go/v2/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 ¶
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 ¶
DeleteDocument delete the document from the index and also delete the HASH key in which the document is stored
func (*Client) DropIndex ¶
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/v2/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) GetTagVals ¶
Get the distinct tags indexed in a Tag field
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 ¶
Info - Get information about the index. This can also be used to check if the index exists
func (*Client) MultiGet ¶
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 ¶
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/v2/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) SpellCheck ¶
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 ¶
SynAdd adds a synonym group. Deprecated: This function is not longer supported on RediSearch 2.0 and above, use SynUpdate instead
type Document ¶
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 ¶
NewDocument creates a document with the specific id and score
func (*Document) EstimateSize ¶
func (*Document) SetPayload ¶
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
Len returns the length of the DocumentList
func (DocumentList) Less ¶
func (l DocumentList) Less(i, j int) bool
func (DocumentList) Swap ¶
func (l DocumentList) Swap(i, j int)
Swap two documents in the list by their index
type Field ¶
Field represents a single field's Schema
func NewGeoField ¶
NewGeoField creates a new geo field with the given name
func NewGeoFieldOptions ¶
func NewGeoFieldOptions(name string, options GeoFieldOptions) Field
NewGeoFieldOptions creates a new geo field with the given name and additional options
func NewNumericField ¶
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 ¶
NewSortableNumericField creates a new numeric field with the given name and a sortable flag
func NewSortableTextField ¶
NewSortableTextField creates a text field with the sortable flag set
func NewTagField ¶
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 ¶
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)
func NewVectorFieldOptions ¶
func NewVectorFieldOptions(name string, options VectorFieldOptions) Field
NewVectorFieldOptions creates a new geo field with the given name and additional options
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 //VectorField allows vector similarity queries against the value in this attribute. VectorField )
Field Types
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 // The query will not filter stopwords QueryWithStopWords Flag = 0x20 DefaultOffset = 0 DefaultNum = 10 )
Query Flags
type GeoFieldOptions ¶
GeoFieldOptions Options for geo fields
type GeoFilterOptions ¶
FilterExpression the results to a given radius from lon and lat. Radius is given as a number and units
type GroupBy ¶
GroupBy groups the results in the pipeline based on one or more properties. Each group should have at least one reducer, a function that handles the group entries, either counting them, or performing multiple aggregate operations.
type HighlightOptions ¶
HighlightOptions represents the options to higlight specific document fields. See http://redisearch.io/Highlight/
type IndexDefinition ¶
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 ¶
func NewIndexDefinition() *IndexDefinition
This is only valid for >= RediSearch 2.0
func (*IndexDefinition) AddPrefix ¶
func (defintion *IndexDefinition) AddPrefix(prefix string) (outDef *IndexDefinition)
This is only valid for >= RediSearch 2.0
func (*IndexDefinition) Serialize ¶
func (defintion *IndexDefinition) Serialize(args redis.Args) redis.Args
This is only valid for >= RediSearch 2.0
func (*IndexDefinition) SetAsync ¶
func (defintion *IndexDefinition) SetAsync(value bool) (outDef *IndexDefinition)
This is only valid for >= RediSearch 2.0
func (*IndexDefinition) SetFilterExpression ¶
func (defintion *IndexDefinition) SetFilterExpression(value string) (outDef *IndexDefinition)
func (*IndexDefinition) SetIndexOn ¶
func (defintion *IndexDefinition) SetIndexOn(value IndexType) (outDef *IndexDefinition)
This is only valid for >= RediSearch 2.2
func (*IndexDefinition) SetLanguage ¶
func (defintion *IndexDefinition) SetLanguage(value string) (outDef *IndexDefinition)
This is only valid for >= RediSearch 2.0
func (*IndexDefinition) SetLanguageField ¶
func (defintion *IndexDefinition) SetLanguageField(value string) (outDef *IndexDefinition)
This is only valid for >= RediSearch 2.0
func (*IndexDefinition) SetPayloadField ¶
func (defintion *IndexDefinition) SetPayloadField(value string) (outDef *IndexDefinition)
This is only valid for >= RediSearch 2.0
func (*IndexDefinition) SetScore ¶
func (defintion *IndexDefinition) SetScore(value float64) (outDef *IndexDefinition)
This is only valid for >= RediSearch 2.0
func (*IndexDefinition) SetScoreField ¶
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 ¶
MisspelledSuggestion is a single suggestion from the spelling corrections
func NewMisspelledSuggestion ¶
func NewMisspelledSuggestion(term string, score float32) MisspelledSuggestion
NewMisspelledSuggestion creates a MisspelledSuggestion with the specific term and score
type MisspelledTerm ¶
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 ¶
func NewMisspelledTerm(term string) MisspelledTerm
func (MisspelledTerm) Len ¶
func (l MisspelledTerm) Len() int
Len returns the length of the MisspelledSuggestionList
func (MisspelledTerm) Less ¶
func (l MisspelledTerm) Less(i, j int) bool
func (MisspelledTerm) Swap ¶
func (l MisspelledTerm) Swap(i, j int)
Swap two suggestions in the list
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 ¶
func NewMultiHostPool ¶
func NewMultiHostPool(hosts []string) *MultiHostPool
func (*MultiHostPool) Close ¶
func (p *MultiHostPool) Close() (err error)
func (*MultiHostPool) Get ¶
func (p *MultiHostPool) Get() redis.Conn
type NumericFieldOptions ¶
NumericFieldOptions Options for numeric fields
type NumericFilterOptions ¶
Limit results to those having numeric values ranging between min and max. min and max follow ZRANGE syntax, and can be -inf, +inf
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 // If set to true, conserves storage space and memory by disabling highlighting support. // Also implied by NoOffsetVectors NoHighlights bool // If set to true, we do not scan and index. SkipInitialScan bool }
Options are flags passed to the the abstract Index call, which receives them as interface{}, allowing for implementation specific options
func NewOptions ¶
func NewOptions() *Options
func (*Options) SetMaxTextFieldsFlag ¶
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) SetNoHighlight ¶
SetNoHighlight conserves storage space and memory by disabling highlighting support.
func (*Options) SetSkipInitialScan ¶
SetSkipInitialScan determines if scan the index on creation
func (*Options) SetStopWords ¶
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 ¶
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 ¶
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 PhoneticMatcherType ¶
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 ¶
func GreaterThan ¶
func GreaterThanEquals ¶
func LessThanEquals ¶
func NewPredicate ¶
type Projection ¶
Projection - Apply a 1-to-1 transformation on one or more properties, and either store the result as a new property down the pipeline, or replace any property using this transformation. Expression is an expression that can be used to perform arithmetic operations on numeric properties, or functions that can be applied on properties depending on their types, or any combination thereof.
func NewProjection ¶
func NewProjection(expression string, alias string) *Projection
func (Projection) Serialize ¶
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 Params map[string]interface{} Dialect int }
Query is a single search query containing all its parameters and predicates
func NewQuery ¶
NewQuery creates a new query for a given index with the given search term. For currently the index parameter is ignored
func (*Query) AddReturnField ¶
AddReturnField adds a single field with AS name that should be returned from each result to the ReturnFields property
func (*Query) AddReturnFields ¶
AddReturnFields adds the fields that should be returned from each result to the ReturnFields property
func (*Query) Highlight ¶
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 ¶
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) SetDialect ¶
SetDialect can have one of 2 options: 1 or 2
func (*Query) SetExpander ¶
SetExpander sets a custom user query expander to be used
func (*Query) SetInFields ¶
SetInFields sets the INFIELDS argument of the query - filter the results to ones appearing only in specific fields of the document
func (*Query) SetInKeys ¶
SetInKeys sets the INKEYS argument of the query - limiting the search to a given set of IDs
func (*Query) SetLanguage ¶
SetLanguage sets the query language, used by the stemmer to expand the query
func (*Query) SetParams ¶
SetParams sets parameters that can be referenced in the query string by a $ , followed by the parameter name, e.g., $user , and each such reference in the search query to a parameter name is substituted by the corresponding parameter value.
func (*Query) SetPayload ¶
SetPayload sets a binary payload to the query, that can be used by custom scoring functions
func (*Query) SetReturnFields ¶
SetReturnFields sets the fields that should be returned from each result. By default we return everything
func (*Query) SetScorer ¶
SetScorer sets an alternative scoring function to be used. The only pre-compiled supported one at the moment is DISMAX
func (*Query) Summarize ¶
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 ¶
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 ¶
func NewReducer(name GroupByReducers, args []string) *Reducer
NewReducer creates a new Reducer object
func NewReducerAlias ¶
func NewReducerAlias(name GroupByReducers, args []string, alias string) *Reducer
NewReducer creates a new Reducer object
func (*Reducer) SetName ¶
func (r *Reducer) SetName(reducer GroupByReducers) *Reducer
type Schema ¶
Schema represents an index schema Schema, or how the index would treat documents sent to it.
type SingleHostPool ¶
func NewSingleHostPool ¶
func NewSingleHostPool(host string) *SingleHostPool
type SortingKey ¶
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 ¶
func NewSortingKeyDir(field string, ascending bool) *SortingKey
func (SortingKey) Serialize ¶
func (s SortingKey) Serialize() redis.Args
type SpellCheckOptions ¶
SpellCheckOptions are options which are passed when performing spelling correction on a query
func NewSpellCheckOptions ¶
func NewSpellCheckOptions(distance int) *SpellCheckOptions
func NewSpellCheckOptionsDefaults ¶
func NewSpellCheckOptionsDefaults() *SpellCheckOptions
func (*SpellCheckOptions) AddExclusionDict ¶
func (s *SpellCheckOptions) AddExclusionDict(dictname string) *SpellCheckOptions
AddExclusionDict adds a custom dictionary named {dictname} to the exclusion list
func (*SpellCheckOptions) AddInclusionDict ¶
func (s *SpellCheckOptions) AddInclusionDict(dictname string) *SpellCheckOptions
AddInclusionDict adds a custom dictionary named {dictname} to the inclusion list
func (*SpellCheckOptions) SetDistance ¶
func (s *SpellCheckOptions) SetDistance(distance int) (*SpellCheckOptions, error)
SetDistance Sets the the maximal Levenshtein distance for spelling suggestions (default: 1, max: 4)
type SuggestOptions ¶
SuggestOptions are options which are passed when recieving suggestions from the Autocompleter
type Suggestion ¶
Suggestion is a single suggestion being added or received from the Autocompleter
func ProcessSugGetVals ¶
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) 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 CaseSensitive bool As string }
TagFieldOptions options for indexing tag fields
type TextFieldOptions ¶
type TextFieldOptions struct { Weight float32 Sortable bool NoStem bool NoIndex bool PhoneticMatcher PhoneticMatcherType As string }
TextFieldOptions Options for text fields - weight and stemming enabled/disabled.
type VectorFieldOptions ¶
type VectorFieldOptions struct { Algorithm algorithm Attributes map[string]interface{} }
VectorFieldOptions Options for vector fields