1# redisearch
2--
3    import "github.com/RedisLabs/redisearch-go/redisearch"
4
5Package redisearch provides a Go client for the RediSearch search engine.
6
7For the full documentation of RediSearch, see
8[https://oss.redislabs.com/redisearch](https://oss.redislabs.com/redisearch)
9
10
11### Example Usage
12
13```go
14
15    import (
16      "github.com/RedisLabs/redisearch-go/redisearch"
17      "log"
18      "fmt"
19    )
20
21    func ExampleClient() {
22      // Create a client. By default a client is schemaless
23      // unless a schema is provided when creating the index
24      c := createClient("myIndex")
25
26      // Create a schema
27      sc := redisearch.NewSchema(redisearch.DefaultOptions).
28        AddField(redisearch.NewTextField("body")).
29        AddField(redisearch.NewTextFieldOptions("title", redisearch.TextFieldOptions{Weight: 5.0, Sortable: true})).
30        AddField(redisearch.NewNumericField("date"))
31
32      // Drop an existing index. If the index does not exist an error is returned
33      c.Drop()
34
35      // Create the index with the given schema
36      if err := c.CreateIndex(sc); err != nil {
37        log.Fatal(err)
38      }
39
40      // Create a document with an id and given score
41      doc := redisearch.NewDocument("doc1", 1.0)
42      doc.Set("title", "Hello world").
43        Set("body", "foo bar").
44        Set("date", time.Now().Unix())
45
46      // Index the document. The API accepts multiple documents at a time
47      if err := c.IndexOptions(redisearch.DefaultIndexingOptions, doc); err != nil {
48        log.Fatal(err)
49      }
50
51      // Searching with limit and sorting
52      docs, total, err := c.Search(redisearch.NewQuery("hello world").
53        Limit(0, 2).
54        SetReturnFields("title"))
55
56      fmt.Println(docs[0].Id, docs[0].Properties["title"], total, err)
57      // Output: doc1 Hello world 1 <nil>
58    }
59
60```
61
62## Usage
63
64```go
65var DefaultIndexingOptions = IndexingOptions{
66	Language: "",
67	NoSave:   false,
68	Replace:  false,
69	Partial:  false,
70}
71```
72DefaultIndexingOptions are the default options for document indexing
73
74```go
75var DefaultOptions = Options{
76	NoSave:          false,
77	NoFieldFlags:    false,
78	NoFrequencies:   false,
79	NoOffsetVectors: false,
80	Stopwords:       nil,
81}
82```
83DefaultOptions represents the default options
84
85#### type Autocompleter
86
87```go
88type Autocompleter struct {
89}
90```
91
92Autocompleter implements a redisearch auto-completer API
93
94#### func  NewAutocompleter
95
96```go
97func NewAutocompleter(addr, name string) *Autocompleter
98```
99NewAutocompleter creates a new Autocompleter with the given host and key name
100
101#### func (*Autocompleter) AddTerms
102
103```go
104func (a *Autocompleter) AddTerms(terms ...Suggestion) error
105```
106AddTerms pushes new term suggestions to the index
107
108#### func (*Autocompleter) Delete
109
110```go
111func (a *Autocompleter) Delete() error
112```
113Delete deletes the Autocompleter key for this AC
114
115#### func (*Autocompleter) Suggest
116
117```go
118func (a *Autocompleter) Suggest(prefix string, num int, fuzzy bool) ([]Suggestion, error)
119```
120Suggest gets completion suggestions from the Autocompleter dictionary to the
121given prefix. If fuzzy is set, we also complete for prefixes that are in 1
122Levenshten distance from the given prefix
123
124#### type Client
125
126```go
127type Client struct {
128}
129```
130
131Client is an interface to redisearch's redis commands
132
133#### func  NewClient
134
135```go
136func NewClient(addr, name string) *Client
137```
138NewClient creates a new client connecting to the redis host, and using the given
139name as key prefix. Addr can be a single host:port pair, or a comma separated
140list of host:port,host:port... In the case of multiple hosts we create a
141multi-pool and select connections at random
142
143#### func (*Client) CreateIndex
144
145```go
146func (i *Client) CreateIndex(s *Schema) error
147```
148CreateIndex configues the index and creates it on redis
149
150#### func (*Client) Drop
151
152```go
153func (i *Client) Drop() error
154```
155Drop the Currentl just flushes the DB - note that this will delete EVERYTHING on
156the redis instance
157
158#### func (*Client) Explain
159
160```go
161func (i *Client) Explain(q *Query) (string, error)
162```
163Explain Return a textual string explaining the query
164
165#### func (*Client) Index
166
167```go
168func (i *Client) Index(docs ...Document) error
169```
170Index indexes a list of documents with the default options
171
172#### func (*Client) IndexOptions
173
174```go
175func (i *Client) IndexOptions(opts IndexingOptions, docs ...Document) error
176```
177IndexOptions indexes multiple documents on the index, with optional Options
178passed to options
179
180#### func (*Client) Info
181
182```go
183func (i *Client) Info() (*IndexInfo, error)
184```
185Info - Get information about the index. This can also be used to check if the
186index exists
187
188#### func (*Client) Search
189
190```go
191func (i *Client) Search(q *Query) (docs []Document, total int, err error)
192```
193Search searches the index for the given query, and returns documents, the total
194number of results, or an error if something went wrong
195
196#### type ConnPool
197
198```go
199type ConnPool interface {
200	Get() redis.Conn
201}
202```
203
204
205#### type Document
206
207```go
208type Document struct {
209	Id         string
210	Score      float32
211	Payload    []byte
212	Properties map[string]interface{}
213}
214```
215
216Document represents a single document to be indexed or returned from a query.
217Besides a score and id, the Properties are completely arbitrary
218
219#### func  NewDocument
220
221```go
222func NewDocument(id string, score float32) Document
223```
224NewDocument creates a document with the specific id and score
225
226#### func (*Document) EstimateSize
227
228```go
229func (d *Document) EstimateSize() (sz int)
230```
231
232#### func (Document) Set
233
234```go
235func (d Document) Set(name string, value interface{}) Document
236```
237Set sets a property and its value in the document
238
239#### func (*Document) SetPayload
240
241```go
242func (d *Document) SetPayload(payload []byte)
243```
244SetPayload Sets the document payload
245
246#### type DocumentList
247
248```go
249type DocumentList []Document
250```
251
252DocumentList is used to sort documents by descending score
253
254#### func (DocumentList) Len
255
256```go
257func (l DocumentList) Len() int
258```
259
260#### func (DocumentList) Less
261
262```go
263func (l DocumentList) Less(i, j int) bool
264```
265
266#### func (DocumentList) Sort
267
268```go
269func (l DocumentList) Sort()
270```
271Sort the DocumentList
272
273#### func (DocumentList) Swap
274
275```go
276func (l DocumentList) Swap(i, j int)
277```
278
279#### type Field
280
281```go
282type Field struct {
283	Name     string
284	Type     FieldType
285	Sortable bool
286	Options  interface{}
287}
288```
289
290Field represents a single field's Schema
291
292#### func  NewNumericField
293
294```go
295func NewNumericField(name string) Field
296```
297NewNumericField creates a new numeric field with the given name
298
299#### func  NewNumericFieldOptions
300
301```go
302func NewNumericFieldOptions(name string, options NumericFieldOptions) Field
303```
304NewNumericFieldOptions defines a numeric field with additional options
305
306#### func  NewSortableNumericField
307
308```go
309func NewSortableNumericField(name string) Field
310```
311NewSortableNumericField creates a new numeric field with the given name and a
312sortable flag
313
314#### func  NewSortableTextField
315
316```go
317func NewSortableTextField(name string, weight float32) Field
318```
319NewSortableTextField creates a text field with the sortable flag set
320
321#### func  NewTagField
322
323```go
324func NewTagField(name string) Field
325```
326NewTagField creates a new text field with default options (separator: ,)
327
328#### func  NewTagFieldOptions
329
330```go
331func NewTagFieldOptions(name string, opts TagFieldOptions) Field
332```
333NewTagFieldOptions creates a new tag field with the given options
334
335#### func  NewTextField
336
337```go
338func NewTextField(name string) Field
339```
340NewTextField creates a new text field with the given weight
341
342#### func  NewTextFieldOptions
343
344```go
345func NewTextFieldOptions(name string, opts TextFieldOptions) Field
346```
347NewTextFieldOptions creates a new text field with given options
348(weight/sortable)
349
350#### type FieldType
351
352```go
353type FieldType int
354```
355
356FieldType is an enumeration of field/property types
357
358```go
359const (
360	// TextField full-text field
361	TextField FieldType = iota
362
363	// NumericField numeric range field
364	NumericField
365
366	// GeoField geo-indexed point field
367	GeoField
368
369	// TagField is a field used for compact indexing of comma separated values
370	TagField
371)
372```
373
374#### type Flag
375
376```go
377type Flag uint64
378```
379
380Flag is a type for query flags
381
382```go
383const (
384	// Treat the terms verbatim and do not perform expansion
385	QueryVerbatim Flag = 0x1
386
387	// Do not load any content from the documents, return just IDs
388	QueryNoContent Flag = 0x2
389
390	// Fetch document scores as well as IDs and fields
391	QueryWithScores Flag = 0x4
392
393	// The query terms must appear in order in the document
394	QueryInOrder Flag = 0x08
395
396	// Fetch document payloads as well as fields. See documentation for payloads on redisearch.io
397	QueryWithPayloads Flag = 0x10
398
399	DefaultOffset = 0
400	DefaultNum    = 10
401)
402```
403Query Flags
404
405#### type HighlightOptions
406
407```go
408type HighlightOptions struct {
409	Fields []string
410	Tags   [2]string
411}
412```
413
414HighlightOptions represents the options to higlight specific document fields.
415See http://redisearch.io/Highlight/
416
417#### type IndexInfo
418
419```go
420type IndexInfo struct {
421	Schema               Schema
422	Name                 string  `redis:"index_name"`
423	DocCount             uint64  `redis:"num_docs"`
424	RecordCount          uint64  `redis:"num_records"`
425	TermCount            uint64  `redis:"num_terms"`
426	MaxDocID             uint64  `redis:"max_doc_id"`
427	InvertedIndexSizeMB  float64 `redis:"inverted_sz_mb"`
428	OffsetVectorSizeMB   float64 `redis:"offset_vector_sz_mb"`
429	DocTableSizeMB       float64 `redis:"doc_table_size_mb"`
430	KeyTableSizeMB       float64 `redis:"key_table_size_mb"`
431	RecordsPerDocAvg     float64 `redis:"records_per_doc_avg"`
432	BytesPerRecordAvg    float64 `redis:"bytes_per_record_avg"`
433	OffsetsPerTermAvg    float64 `redis:"offsets_per_term_avg"`
434	OffsetBitsPerTermAvg float64 `redis:"offset_bits_per_record_avg"`
435}
436```
437
438IndexInfo - Structure showing information about an existing index
439
440#### type IndexingOptions
441
442```go
443type IndexingOptions struct {
444	Language string
445	NoSave   bool
446	Replace  bool
447	Partial  bool
448}
449```
450
451IndexingOptions represent the options for indexing a single document
452
453#### type MultiError
454
455```go
456type MultiError []error
457```
458
459MultiError Represents one or more errors
460
461#### func  NewMultiError
462
463```go
464func NewMultiError(len int) MultiError
465```
466NewMultiError initializes a multierror with the given len, and all sub-errors
467set to nil
468
469#### func (MultiError) Error
470
471```go
472func (e MultiError) Error() string
473```
474Error returns a string representation of the error, in this case it just chains
475all the sub errors if they are not nil
476
477#### type MultiHostPool
478
479```go
480type MultiHostPool struct {
481	sync.Mutex
482}
483```
484
485
486#### func  NewMultiHostPool
487
488```go
489func NewMultiHostPool(hosts []string) *MultiHostPool
490```
491
492#### func (*MultiHostPool) Get
493
494```go
495func (p *MultiHostPool) Get() redis.Conn
496```
497
498#### type NumericFieldOptions
499
500```go
501type NumericFieldOptions struct {
502	Sortable bool
503	NoIndex  bool
504}
505```
506
507NumericFieldOptions Options for numeric fields
508
509#### type Operator
510
511```go
512type Operator string
513```
514
515
516```go
517const (
518	Eq Operator = "="
519
520	Gt  Operator = ">"
521	Gte Operator = ">="
522
523	Lt  Operator = "<"
524	Lte Operator = "<="
525
526	Between          Operator = "BETWEEN"
527	BetweenInclusive Operator = "BETWEEEN_EXCLUSIVE"
528)
529```
530
531#### type Options
532
533```go
534type Options struct {
535
536	// If set, we will not save the documents contents, just index them, for fetching ids only
537	NoSave bool
538
539	NoFieldFlags bool
540
541	NoFrequencies bool
542
543	NoOffsetVectors bool
544
545	Stopwords []string
546}
547```
548
549Options are flags passed to the the abstract Index call, which receives them as
550interface{}, allowing for implementation specific options
551
552#### type Paging
553
554```go
555type Paging struct {
556	Offset int
557	Num    int
558}
559```
560
561Paging represents the offset paging of a search result
562
563#### type Predicate
564
565```go
566type Predicate struct {
567	Property string
568	Operator Operator
569	Value    []interface{}
570}
571```
572
573
574#### func  Equals
575
576```go
577func Equals(property string, value interface{}) Predicate
578```
579
580#### func  GreaterThan
581
582```go
583func GreaterThan(property string, value interface{}) Predicate
584```
585
586#### func  GreaterThanEquals
587
588```go
589func GreaterThanEquals(property string, value interface{}) Predicate
590```
591
592#### func  InRange
593
594```go
595func InRange(property string, min, max interface{}, inclusive bool) Predicate
596```
597
598#### func  LessThan
599
600```go
601func LessThan(property string, value interface{}) Predicate
602```
603
604#### func  LessThanEquals
605
606```go
607func LessThanEquals(property string, value interface{}) Predicate
608```
609
610#### func  NewPredicate
611
612```go
613func NewPredicate(property string, operator Operator, values ...interface{}) Predicate
614```
615
616#### type Query
617
618```go
619type Query struct {
620	Raw string
621
622	Paging Paging
623	Flags  Flag
624	Slop   int
625
626	Filters       []Predicate
627	InKeys        []string
628	ReturnFields  []string
629	Language      string
630	Expander      string
631	Scorer        string
632	Payload       []byte
633	SortBy        *SortingKey
634	HighlightOpts *HighlightOptions
635	SummarizeOpts *SummaryOptions
636}
637```
638
639Query is a single search query and all its parameters and predicates
640
641#### func  NewQuery
642
643```go
644func NewQuery(raw string) *Query
645```
646NewQuery creates a new query for a given index with the given search term. For
647currently the index parameter is ignored
648
649#### func (*Query) Highlight
650
651```go
652func (q *Query) Highlight(fields []string, openTag, closeTag string) *Query
653```
654Highlight sets highighting on given fields. Highlighting marks all the query
655terms with the given open and close tags (i.e. <b> and </b> for HTML)
656
657#### func (*Query) Limit
658
659```go
660func (q *Query) Limit(offset, num int) *Query
661```
662Limit sets the paging offset and limit for the query
663
664#### func (*Query) SetExpander
665
666```go
667func (q *Query) SetExpander(exp string) *Query
668```
669SetExpander sets a custom user query expander to be used
670
671#### func (*Query) SetFlags
672
673```go
674func (q *Query) SetFlags(flags Flag) *Query
675```
676SetFlags sets the query's optional flags
677
678#### func (*Query) SetInKeys
679
680```go
681func (q *Query) SetInKeys(keys ...string) *Query
682```
683SetInKeys sets the INKEYS argument of the query - limiting the search to a given
684set of IDs
685
686#### func (*Query) SetLanguage
687
688```go
689func (q *Query) SetLanguage(lang string) *Query
690```
691SetLanguage sets the query language, used by the stemmer to expand the query
692
693#### func (*Query) SetPayload
694
695```go
696func (q *Query) SetPayload(payload []byte) *Query
697```
698SetPayload sets a binary payload to the query, that can be used by custom
699scoring functions
700
701#### func (*Query) SetReturnFields
702
703```go
704func (q *Query) SetReturnFields(fields ...string) *Query
705```
706SetReturnFields sets the fields that should be returned from each result. By
707default we return everything
708
709#### func (*Query) SetScorer
710
711```go
712func (q *Query) SetScorer(scorer string) *Query
713```
714SetScorer sets an alternative scoring function to be used. The only pre-compiled
715supported one at the moment is DISMAX
716
717#### func (*Query) SetSortBy
718
719```go
720func (q *Query) SetSortBy(field string, ascending bool) *Query
721```
722SetSortBy sets the sorting key for the query
723
724#### func (*Query) Summarize
725
726```go
727func (q *Query) Summarize(fields ...string) *Query
728```
729Summarize sets summarization on the given list of fields. It will instruct the
730engine to extract the most relevant snippets from the fields and return them as
731the field content. This function works with the default values of the engine,
732and only sets the fields. There is a function that accepts all options -
733SummarizeOptions
734
735#### func (*Query) SummarizeOptions
736
737```go
738func (q *Query) SummarizeOptions(opts SummaryOptions) *Query
739```
740SummarizeOptions sets summarization on the given list of fields. It will
741instruct the engine to extract the most relevant snippets from the fields and
742return them as the field content.
743
744This function accepts advanced settings for snippet length, separators and
745number of snippets
746
747#### type Schema
748
749```go
750type Schema struct {
751	Fields  []Field
752	Options Options
753}
754```
755
756Schema represents an index schema Schema, or how the index would treat documents
757sent to it.
758
759#### func  NewSchema
760
761```go
762func NewSchema(opts Options) *Schema
763```
764NewSchema creates a new Schema object
765
766#### func (*Schema) AddField
767
768```go
769func (m *Schema) AddField(f Field) *Schema
770```
771AddField adds a field to the Schema object
772
773#### type SingleHostPool
774
775```go
776type SingleHostPool struct {
777	*redis.Pool
778}
779```
780
781
782#### func  NewSingleHostPool
783
784```go
785func NewSingleHostPool(host string) *SingleHostPool
786```
787
788#### type SortingKey
789
790```go
791type SortingKey struct {
792	Field     string
793	Ascending bool
794}
795```
796
797SortingKey represents the sorting option if the query needs to be sorted based
798on a sortable fields and not a ranking function. See
799http://redisearch.io/Sorting/
800
801#### type Suggestion
802
803```go
804type Suggestion struct {
805	Term    string
806	Score   float64
807	Payload string
808}
809```
810
811Suggestion is a single suggestion being added or received from the Autocompleter
812
813#### type SuggestionList
814
815```go
816type SuggestionList []Suggestion
817```
818
819SuggestionList is a sortable list of suggestions returned from an engine
820
821#### func (SuggestionList) Len
822
823```go
824func (l SuggestionList) Len() int
825```
826
827#### func (SuggestionList) Less
828
829```go
830func (l SuggestionList) Less(i, j int) bool
831```
832
833#### func (SuggestionList) Sort
834
835```go
836func (l SuggestionList) Sort()
837```
838Sort the SuggestionList
839
840#### func (SuggestionList) Swap
841
842```go
843func (l SuggestionList) Swap(i, j int)
844```
845
846#### type SummaryOptions
847
848```go
849type SummaryOptions struct {
850	Fields       []string
851	FragmentLen  int    // default 20
852	NumFragments int    // default 3
853	Separator    string // default "..."
854}
855```
856
857SummaryOptions represents the configuration used to create field summaries. See
858http://redisearch.io/Highlight/
859
860#### type TagFieldOptions
861
862```go
863type TagFieldOptions struct {
864	// Separator is the custom separator between tags. defaults to comma (,)
865	Separator byte
866	NoIndex   bool
867}
868```
869
870TagFieldOptions options for indexing tag fields
871
872#### type TextFieldOptions
873
874```go
875type TextFieldOptions struct {
876	Weight   float32
877	Sortable bool
878	NoStem   bool
879	NoIndex  bool
880}
881```
882
883TextFieldOptions Options for text fields - weight and stemming enabled/disabled.
884