redisearch

-- import “github.com/RedisLabs/redisearch-go/redisearch”

Package redisearch provides a Go client for the RediSearch search engine.

For the full documentation of RediSearch, see http://redisearch.io

Example Usage

  1. import (
  2. "github.com/RedisLabs/redisearch-go/redisearch"
  3. "log"
  4. "fmt"
  5. )
  6. func ExampleClient() {
  7. // Create a client. By default a client is schemaless
  8. // unless a schema is provided when creating the index
  9. c := createClient("myIndex")
  10. // Create a schema
  11. sc := redisearch.NewSchema(redisearch.DefaultOptions).
  12. AddField(redisearch.NewTextField("body")).
  13. AddField(redisearch.NewTextFieldOptions("title", redisearch.TextFieldOptions{Weight: 5.0, Sortable: true})).
  14. AddField(redisearch.NewNumericField("date"))
  15. // Drop an existing index. If the index does not exist an error is returned
  16. c.Drop()
  17. // Create the index with the given schema
  18. if err := c.CreateIndex(sc); err != nil {
  19. log.Fatal(err)
  20. }
  21. // Create a document with an id and given score
  22. doc := redisearch.NewDocument("doc1", 1.0)
  23. doc.Set("title", "Hello world").
  24. Set("body", "foo bar").
  25. Set("date", time.Now().Unix())
  26. // Index the document. The API accepts multiple documents at a time
  27. if err := c.IndexOptions(redisearch.DefaultIndexingOptions, doc); err != nil {
  28. log.Fatal(err)
  29. }
  30. // Searching with limit and sorting
  31. docs, total, err := c.Search(redisearch.NewQuery("hello world").
  32. Limit(0, 2).
  33. SetReturnFields("title"))
  34. fmt.Println(docs[0].Id, docs[0].Properties["title"], total, err)
  35. // Output: doc1 Hello world 1 <nil>
  36. }

Usage

  1. var DefaultIndexingOptions = IndexingOptions{
  2. Language: "",
  3. NoSave: false,
  4. Replace: false,
  5. Partial: false,
  6. }

DefaultIndexingOptions are the default options for document indexing

  1. var DefaultOptions = Options{
  2. NoSave: false,
  3. NoFieldFlags: false,
  4. NoFrequencies: false,
  5. NoOffsetVectors: false,
  6. Stopwords: nil,
  7. }

DefaultOptions represents the default options

type Autocompleter

  1. type Autocompleter struct {
  2. }

Autocompleter implements a redisearch auto-completer API

func NewAutocompleter

  1. func NewAutocompleter(addr, name string) *Autocompleter

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

func (*Autocompleter) AddTerms

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

AddTerms pushes new term suggestions to the index

func (*Autocompleter) Delete

  1. func (a *Autocompleter) Delete() error

Delete deletes the Autocompleter key for this AC

func (*Autocompleter) Suggest

  1. func (a *Autocompleter) Suggest(prefix string, num int, fuzzy bool) ([]Suggestion, 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

type Client

  1. type Client struct {
  2. }

Client is an interface to redisearch’s redis commands

func NewClient

  1. 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

func (*Client) CreateIndex

  1. func (i *Client) CreateIndex(s *Schema) error

CreateIndex configues the index and creates it on redis

func (*Client) Drop

  1. func (i *Client) Drop() error

Drop the Currentl just flushes the DB - note that this will delete EVERYTHING on the redis instance

func (*Client) Explain

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

Explain Return a textual string explaining the query

func (*Client) Index

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

Index indexes a list of documents with the default options

func (*Client) IndexOptions

  1. 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

  1. 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) Search

  1. 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

type ConnPool

  1. type ConnPool interface {
  2. Get() redis.Conn
  3. }

type Document

  1. type Document struct {
  2. Id string
  3. Score float32
  4. Payload []byte
  5. Properties map[string]interface{}
  6. }

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

  1. func NewDocument(id string, score float32) Document

NewDocument creates a document with the specific id and score

func (*Document) EstimateSize

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

func (Document) Set

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

Set sets a property and its value in the document

func (*Document) SetPayload

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

SetPayload Sets the document payload

type DocumentList

  1. type DocumentList []Document

DocumentList is used to sort documents by descending score

func (DocumentList) Len

  1. func (l DocumentList) Len() int

func (DocumentList) Less

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

func (DocumentList) Sort

  1. func (l DocumentList) Sort()

Sort the DocumentList

func (DocumentList) Swap

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

type Field

  1. type Field struct {
  2. Name string
  3. Type FieldType
  4. Sortable bool
  5. Options interface{}
  6. }

Field represents a single field’s Schema

func NewNumericField

  1. func NewNumericField(name string) Field

NewNumericField creates a new numeric field with the given name

func NewNumericFieldOptions

  1. func NewNumericFieldOptions(name string, options NumericFieldOptions) Field

NewNumericFieldOptions defines a numeric field with additional options

func NewSortableNumericField

  1. func NewSortableNumericField(name string) Field

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

func NewSortableTextField

  1. func NewSortableTextField(name string, weight float32) Field

NewSortableTextField creates a text field with the sortable flag set

func NewTagField

  1. func NewTagField(name string) Field

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

func NewTagFieldOptions

  1. func NewTagFieldOptions(name string, opts TagFieldOptions) Field

NewTagFieldOptions creates a new tag field with the given options

func NewTextField

  1. func NewTextField(name string) Field

NewTextField creates a new text field with the given weight

func NewTextFieldOptions

  1. func NewTextFieldOptions(name string, opts TextFieldOptions) Field

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

type FieldType

  1. type FieldType int

FieldType is an enumeration of field/property types

  1. const (
  2. // TextField full-text field
  3. TextField FieldType = iota
  4. // NumericField numeric range field
  5. NumericField
  6. // GeoField geo-indexed point field
  7. GeoField
  8. // TagField is a field used for compact indexing of comma separated values
  9. TagField
  10. )

type Flag

  1. type Flag uint64

Flag is a type for query flags

  1. const (
  2. // Treat the terms verbatim and do not perform expansion
  3. QueryVerbatim Flag = 0x1
  4. // Do not load any content from the documents, return just IDs
  5. QueryNoContent Flag = 0x2
  6. // Fetch document scores as well as IDs and fields
  7. QueryWithScores Flag = 0x4
  8. // The query terms must appear in order in the document
  9. QueryInOrder Flag = 0x08
  10. // Fetch document payloads as well as fields. See documentation for payloads on redisearch.io
  11. QueryWithPayloads Flag = 0x10
  12. DefaultOffset = 0
  13. DefaultNum = 10
  14. )

Query Flags

type HighlightOptions

  1. type HighlightOptions struct {
  2. Fields []string
  3. Tags [2]string
  4. }

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

type IndexInfo

  1. type IndexInfo struct {
  2. Schema Schema
  3. Name string `redis:"index_name"`
  4. DocCount uint64 `redis:"num_docs"`
  5. RecordCount uint64 `redis:"num_records"`
  6. TermCount uint64 `redis:"num_terms"`
  7. MaxDocID uint64 `redis:"max_doc_id"`
  8. InvertedIndexSizeMB float64 `redis:"inverted_sz_mb"`
  9. OffsetVectorSizeMB float64 `redis:"offset_vector_sz_mb"`
  10. DocTableSizeMB float64 `redis:"doc_table_size_mb"`
  11. KeyTableSizeMB float64 `redis:"key_table_size_mb"`
  12. RecordsPerDocAvg float64 `redis:"records_per_doc_avg"`
  13. BytesPerRecordAvg float64 `redis:"bytes_per_record_avg"`
  14. OffsetsPerTermAvg float64 `redis:"offsets_per_term_avg"`
  15. OffsetBitsPerTermAvg float64 `redis:"offset_bits_per_record_avg"`
  16. }

IndexInfo - Structure showing information about an existing index

type IndexingOptions

  1. type IndexingOptions struct {
  2. Language string
  3. NoSave bool
  4. Replace bool
  5. Partial bool
  6. }

IndexingOptions represent the options for indexing a single document

type MultiError

  1. type MultiError []error

MultiError Represents one or more errors

func NewMultiError

  1. func NewMultiError(len int) MultiError

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

func (MultiError) Error

  1. 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

  1. type MultiHostPool struct {
  2. sync.Mutex
  3. }

func NewMultiHostPool

  1. func NewMultiHostPool(hosts []string) *MultiHostPool

func (*MultiHostPool) Get

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

type NumericFieldOptions

  1. type NumericFieldOptions struct {
  2. Sortable bool
  3. NoIndex bool
  4. }

NumericFieldOptions Options for numeric fields

type Operator

  1. type Operator string
  1. const (
  2. Eq Operator = "="
  3. Gt Operator = ">"
  4. Gte Operator = ">="
  5. Lt Operator = "<"
  6. Lte Operator = "<="
  7. Between Operator = "BETWEEN"
  8. BetweenInclusive Operator = "BETWEEEN_EXCLUSIVE"
  9. )

type Options

  1. type Options struct {
  2. // If set, we will not save the documents contents, just index them, for fetching ids only
  3. NoSave bool
  4. NoFieldFlags bool
  5. NoFrequencies bool
  6. NoOffsetVectors bool
  7. Stopwords []string
  8. }

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

type Paging

  1. type Paging struct {
  2. Offset int
  3. Num int
  4. }

Paging represents the offset paging of a search result

type Predicate

  1. type Predicate struct {
  2. Property string
  3. Operator Operator
  4. Value []interface{}
  5. }

func Equals

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

func GreaterThan

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

func GreaterThanEquals

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

func InRange

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

func LessThan

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

func LessThanEquals

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

func NewPredicate

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

type Query

  1. type Query struct {
  2. Raw string
  3. Paging Paging
  4. Flags Flag
  5. Slop int
  6. Filters []Predicate
  7. InKeys []string
  8. ReturnFields []string
  9. Language string
  10. Expander string
  11. Scorer string
  12. Payload []byte
  13. SortBy *SortingKey
  14. HighlightOpts *HighlightOptions
  15. SummarizeOpts *SummaryOptions
  16. }

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

func NewQuery

  1. 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) Highlight

  1. 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. and for HTML)

func (*Query) Limit

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

Limit sets the paging offset and limit for the query

func (*Query) SetExpander

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

SetExpander sets a custom user query expander to be used

func (*Query) SetFlags

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

SetFlags sets the query’s optional flags

func (*Query) SetInKeys

  1. 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

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

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

func (*Query) SetPayload

  1. 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

  1. 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

  1. 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

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

SetSortBy sets the sorting key for the query

func (*Query) Summarize

  1. 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

  1. 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 Schema

  1. type Schema struct {
  2. Fields []Field
  3. Options Options
  4. }

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

func NewSchema

  1. func NewSchema(opts Options) *Schema

NewSchema creates a new Schema object

func (*Schema) AddField

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

AddField adds a field to the Schema object

type SingleHostPool

  1. type SingleHostPool struct {
  2. *redis.Pool
  3. }

func NewSingleHostPool

  1. func NewSingleHostPool(host string) *SingleHostPool

type SortingKey

  1. type SortingKey struct {
  2. Field string
  3. Ascending bool
  4. }

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/

type Suggestion

  1. type Suggestion struct {
  2. Term string
  3. Score float64
  4. Payload string
  5. }

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

type SuggestionList

  1. type SuggestionList []Suggestion

SuggestionList is a sortable list of suggestions returned from an engine

func (SuggestionList) Len

  1. func (l SuggestionList) Len() int

func (SuggestionList) Less

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

func (SuggestionList) Sort

  1. func (l SuggestionList) Sort()

Sort the SuggestionList

func (SuggestionList) Swap

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

type SummaryOptions

  1. type SummaryOptions struct {
  2. Fields []string
  3. FragmentLen int // default 20
  4. NumFragments int // default 3
  5. Separator string // default "..."
  6. }

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

type TagFieldOptions

  1. type TagFieldOptions struct {
  2. // Separator is the custom separator between tags. defaults to comma (,)
  3. Separator byte
  4. NoIndex bool
  5. }

TagFieldOptions options for indexing tag fields

type TextFieldOptions

  1. type TextFieldOptions struct {
  2. Weight float32
  3. Sortable bool
  4. NoStem bool
  5. NoIndex bool
  6. }

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