search

package
v1.0.0-beta.36 Latest Latest
Warning

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

Go to latest
Published: May 8, 2023 License: Apache-2.0 Imports: 12 Imported by: 2

Documentation

Overview

Package search provides an interface for accessing Tigris data-platform search APIs.

Index

Examples

Constants

This section is empty.

Variables

View Source
var DefaultFacetQuery = FacetQuery{FacetFields: map[string]FacetQueryOptions{}, /* contains filtered or unexported fields */}
View Source
var DefaultFacetQueryOptions = FacetQueryOptions{Size: 10}
View Source
var DefaultSearchOptions = Options{Page: 1, PageSize: 20}

Functions

This section is empty.

Types

type Collation

type Collation struct {
	// Case is case-sensitive by default, to perform case-insensitive query override it and set
	// this to 'ci'.
	Case string
}

Collation allows you to specify string comparison rules. Default is case-sensitive.

type Config

type Config struct {
	TLS          *tls.Config `json:"tls,omitempty"`
	ClientID     string      `json:"client_id,omitempty"`
	ClientSecret string      `json:"client_secret,omitempty"`
	Token        string      `json:"token,omitempty"`
	URL          string      `json:"url,omitempty"`
	Protocol     string      `json:"protocol,omitempty"`
	Project      string      `json:"project,omitempty"`
	Branch       string      `json:"branch,omitempty"`
	// MustExist if set skips implicit database creation
	MustExist bool
}

type DeleteResponse

type DeleteResponse struct{}

DeleteResponse includes metadata about just deleted documents. Returned by Delete-documents collection API.

type DocStatus

type DocStatus struct {
	ID    string `json:"id"`
	Error error
}

type Error

type Error driver.Error

func NewError

func NewError(c code.Code, format string, a ...interface{}) *Error

func (*Error) AsTigrisError

func (e *Error) AsTigrisError(de *driver.Error) bool

AsTigrisError needed to convert driver.Error to search.Error when called by errors.As(driver.Error, *search.Error) see driver.Error.As for more information.

type Facet

type Facet struct {
	// Counts represent distinct field values and number of times they appear in a faceted field
	Counts []FacetCount
	Stats  FacetStats
}

Facet represents unique values with counts and aggregated summary of values in a faceted field.

func (*Facet) From

func (f *Facet) From(apiFacet *api.SearchFacet)

From constructs Facet from Tigris server's search response sets default values for missing/nil input.

type FacetCount

type FacetCount struct {
	Count int64
	Value string
}

FacetCount represents number/ Count of times a Value appeared in the faceted field.

func (*FacetCount) From

func (f *FacetCount) From(apiFacetCount *api.FacetCount)

From constructs FacetCount from Tigris server's search response sets default values for missing/nil input.

type FacetQuery

type FacetQuery struct {
	FacetFields map[string]FacetQueryOptions
	// contains filtered or unexported fields
}

func (*FacetQuery) Built

func (f *FacetQuery) Built() (driver.Facet, error)

Built marshals the facet query.

type FacetQueryBuilder

type FacetQueryBuilder interface {
	// WithFields would add fields to query with default query options
	WithFields(...string) FacetQueryBuilder
	WithFieldAndOption(string, FacetQueryOptions) FacetQueryBuilder
	WithFieldOptions(map[string]FacetQueryOptions) FacetQueryBuilder
	Build() *FacetQuery
}

func NewFacetQueryBuilder

func NewFacetQueryBuilder() FacetQueryBuilder

type FacetQueryOptions

type FacetQueryOptions struct{ Size int }

type FacetStats

type FacetStats struct {
	// Average of all values in a field. Only available for numeric fields
	Avg *float64
	// Maximum of all values in a field. Only available for numeric fields
	Max *float64
	// Minimum of all values in a field. Only available for numeric fields
	Min *float64
	// Sum of all values in a field. Only available for numeric fields
	Sum *float64
	// Total number of values in a field
	Count int64
}

FacetStats represent statistics for the faceted field.

func (*FacetStats) From

func (f *FacetStats) From(apiFacet *api.FacetStats)

From constructs FacetStats from Tigris server's search response sets default values for missing/nil input.

type Hit

type Hit[T schema.Model] struct {
	// Document represents the matched collection document unmarshalled into type T
	Document *T
	// Meta is the relevance metadata for this collection document
	Meta *HitMeta
}

Hit represents a matched document for search query and relevant matching metadata.

func (*Hit[T]) From

func (h *Hit[T]) From(apiHit *api.SearchHit) error

From constructs a Hit by unmarshalling the response as Collection Type T throws error if json unmarshalling fails.

type HitMeta

type HitMeta struct {
	// CreatedAt is the time at which document was inserted/replaced
	// Measured in nanoseconds since the UTC Unix epoch.
	CreatedAt *time.Time
	// UpdatedAt is the time at which document was inserted/replaced
	// Measured in nanoseconds since the UTC Unix epoch.
	UpdatedAt *time.Time
}

HitMeta represents the metadata associated with a search hit.

func (*HitMeta) From

func (hm *HitMeta) From(apiHitMeta *api.SearchHitMeta)

From constructs HitMeta from Tigris server's response.

type Index

type Index[T schema.Model] struct {
	Name         string
	SearchClient driver.SearchClient
}

Index provides an interface for documents manipulation. Such as Insert, Update, Delete, Read.

func GetIndex

func GetIndex[T schema.Model](s *Search) *Index[T]

GetIndex returns index object corresponding to index model T.

func (*Index[T]) Create

func (c *Index[T]) Create(ctx context.Context, docs ...*T) (*Response, error)

Create is used for indexing a single or multiple documents. The API expects an array of documents. Each document is a JSON object. An "id" is optional and the server can automatically generate it for you in case it is missing. In cases when an id is provided in the document and the document already exists then that document will not be indexed and in the response there will be an error corresponding to that document id other documents will succeed. Returns an array of status indicating the status of each document.

func (*Index[T]) CreateOrReplace

func (c *Index[T]) CreateOrReplace(ctx context.Context, docs ...*T) (*Response, error)

CreateOrReplace creates or replaces one or more documents. Each document is a JSON object. A document is replaced if it already exists. An "id" is generated automatically in case it is missing in the document. The document is created if "id" doesn't exist otherwise it is replaced. Returns an array of status indicating the status of each document.

func (*Index[T]) Delete

func (c *Index[T]) Delete(ctx context.Context, ids []string) (*Response, error)

Delete one or more documents by id. Returns an array of status indicating the status of each document. Each status has an error field that is set to null in case document is deleted successfully otherwise it will be non-null with an error code and message.

func (*Index[T]) DeleteByQuery

func (c *Index[T]) DeleteByQuery(ctx context.Context, filter filter.Filter) (int, error)

DeleteByQuery is used to delete documents that match the filter. A filter is required. To delete document by id, you can pass the filter as follows ```{"id": "test"}```. Returns a count of number of documents deleted.

func (*Index[T]) DeleteOne

func (c *Index[T]) DeleteOne(ctx context.Context, id string) error

DeleteOne deletes one document.

func (*Index[T]) Get

func (c *Index[T]) Get(ctx context.Context, ids []string) ([]T, error)

Get retrieves one or more documents by id. The response is an array of documents in the same order it is requests. A null is returned for the documents that are not found.

func (*Index[T]) GetOne

func (c *Index[T]) GetOne(ctx context.Context, id string) (*T, error)

GetOne retrieves one document.

func (*Index[T]) Search

func (c *Index[T]) Search(ctx context.Context, req *Request) (*Iterator[T], error)

Search returns Iterator which iterates over matched documents in the index.

func (*Index[T]) Update

func (c *Index[T]) Update(ctx context.Context, docs ...*T) (*Response, error)

Update updates one or more documents by "id". Each document is required to have the "id" field in it. Returns an array of status indicating the status of each document. Each status has an error field that is set to null in case document is updated successfully otherwise the error field is set with a code and message.

type IndexDoc

type IndexDoc[T any] struct {
	Document T

	Metadata
}

type Iterator

type Iterator[T interface{}] struct {
	Iterator driver.SearchIndexResultIterator
	// contains filtered or unexported fields
}

Iterator is used to iterate search documents.

func (*Iterator[T]) Close

func (it *Iterator[T]) Close()

Close closes Iterator stream.

func (*Iterator[T]) Err

func (it *Iterator[T]) Err() error

Err returns nil if iteration was successful, otherwise return error details.

func (*Iterator[T]) Next

func (it *Iterator[T]) Next(res *Result[T]) bool

type Meta

type Meta struct {
	// Found represents total number of results matching the search query
	Found int64
	// TotalPages represent the total number of pages of search results
	TotalPages int32
	// Page represents pagination metadata for current page
	Page Page
}

Meta represents search response metadata from server.

func (*Meta) From

func (m *Meta) From(apiMeta *api.SearchMetadata)

From constructs Meta from Tigris server's search response metadata sets default values for missing/nil input.

type Metadata

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

func (*Metadata) GetCreatedAt

func (m *Metadata) GetCreatedAt() time.Time

GetCreatedAt returns time of document creation.

func (*Metadata) GetUpdatedAt

func (m *Metadata) GetUpdatedAt() time.Time

GetUpdatedAt returns time of last document update.

type Options

type Options struct {
	Page      int32
	PageSize  int32
	Collation *driver.Collation
}

type Page

type Page struct {
	// Current page number for the paginated search results
	Current int32
	// Size represents maximum number of search results displayed per page
	Size int32
}

Page includes pagination metadata for search results.

func (*Page) From

func (p *Page) From(apiPage *api.Page)

From constructs a Page from the Tigris server's search response sets default values for missing/nil input.

type Request

type Request struct {
	// Q is the text search query associated with this request
	Q string
	// Optional SearchFields is an array of fields to project Q against
	// if not specified, query will be projected against all searchable fields
	SearchFields map[string]bool
	// Optional Filter is applied on search results to further refine them
	Filter filter.Filter
	// Optional Facet query can be used to request categorical arrangement of the indexed terms
	Facet *FacetQuery
	// Optional Sort order can be specified to order the search results
	Sort sort.Order
	// Optional IncludeFields sets the document fields to include in search results
	// By default, all documents fields will be included, unless ExcludeFields is specified
	IncludeFields []string
	// Optional ExcludeFields sets the document fields that shouldn't be included in results
	ExcludeFields []string
	// Vector is the map of fields for vector search
	Vector VectorType
	// Optional Options provide pagination input
	Options *Options
}

Request for search.

func (*Request) Build

func (r *Request) Build() *Request

func (*Request) BuildInternal

func (r *Request) BuildInternal() (*driver.SearchRequest, error)

func (*Request) WithExcludeFields

func (r *Request) WithExcludeFields(fields ...string) RequestBuilder

func (*Request) WithFacet

func (r *Request) WithFacet(facet *FacetQuery) RequestBuilder

func (*Request) WithFacetFields

func (r *Request) WithFacetFields(fields ...string) RequestBuilder

func (*Request) WithFilter

func (r *Request) WithFilter(f filter.Filter) RequestBuilder

func (*Request) WithIncludeFields

func (r *Request) WithIncludeFields(fields ...string) RequestBuilder

func (*Request) WithOptions

func (r *Request) WithOptions(options *Options) RequestBuilder

func (*Request) WithQuery

func (r *Request) WithQuery(q string) RequestBuilder

func (*Request) WithSearchFields

func (r *Request) WithSearchFields(fields ...string) RequestBuilder

func (*Request) WithSortOrder

func (r *Request) WithSortOrder(sortOrder sort.Order) RequestBuilder

func (*Request) WithSorting

func (r *Request) WithSorting(sortByFields ...sort.Order) RequestBuilder

func (*Request) WithVectorSearch

func (r *Request) WithVectorSearch(field string, value []float64) RequestBuilder

type RequestBuilder

type RequestBuilder interface {
	WithQuery(q string) RequestBuilder
	WithSearchFields(fields ...string) RequestBuilder
	WithFilter(filter.Filter) RequestBuilder
	WithFacetFields(fields ...string) RequestBuilder
	WithFacet(*FacetQuery) RequestBuilder
	WithSorting(sortByFields ...sort.Order) RequestBuilder
	WithSortOrder(sortOrder sort.Order) RequestBuilder
	WithIncludeFields(fields ...string) RequestBuilder
	WithExcludeFields(fields ...string) RequestBuilder
	WithOptions(*Options) RequestBuilder
	WithVectorSearch(field string, value []float64) RequestBuilder
	Build() *Request
}

func MatchAll

func MatchAll() RequestBuilder

func NewRequestBuilder

func NewRequestBuilder() RequestBuilder
Example
req := NewRequestBuilder().WithQuery("my search text").Build()
fmt.Println(req.Q)
Output:

my search text

type Response

type Response struct {
	Statuses []DocStatus
}

type Result

type Result[T schema.Model] struct {
	// Hits is the results of the query as a list
	Hits []Hit[T]
	// Facets contain the facet distribution of any requested faceted fields
	Facets map[string]Facet
	// Meta represents metadata associated with this search result
	Meta Meta
}

Result represents response to a search query.

func (*Result[T]) From

func (result *Result[T]) From(apiResponse *api.SearchResponse) error

func (*Result[T]) FromHits

func (result *Result[T]) FromHits(hits []*api.SearchHit) error

func (*Result[T]) FromIndexResponse

func (result *Result[T]) FromIndexResponse(apiResponse *api.SearchIndexResponse) error
type Search struct {
	// contains filtered or unexported fields
}

Search is the interface for interacting with a Tigris Search Due to the limitations of Golang generics instantiations of the indexs should be done using GetIndex[Model](ctx, db) top level function instead of method of this interface. Similarly to get access to index APIs in a transaction top level GetTxIndex(ctx, tx) function should be used instead of method of Tx interface.

func MustOpen

func MustOpen(ctx context.Context, cfg *Config, models ...schema.Model) *Search
Example
package main

import (
	"context"

	"github.com/tigrisdata/tigris-client-go/search"
)

func main() {
	ctx := context.TODO()

	type Coll1 struct {
		Field1 string
	}

	s := search.MustOpen(ctx, &search.Config{Project: "db1"}, &Coll1{})

	idx := search.GetIndex[Coll1](s)

	if _, err := idx.Create(ctx, &Coll1{"aaa"}); err != nil {
		panic(err)
	}
}
Output:

func NewSearch

func NewSearch(name string, search driver.SearchClient) *Search

func Open

func Open(ctx context.Context, cfg *Config, models ...schema.Model) (*Search, error)

func (*Search) CreateIndexes

func (s *Search) CreateIndexes(ctx context.Context, model schema.Model, models ...schema.Model) error

CreateIndexes creates indexes in the Search using provided index models This method is only needed if indexes need to be created dynamically, all static indexes are created by OpenSearch.

func (*Search) DeleteIndex

func (s *Search) DeleteIndex(ctx context.Context, model schema.Model, models ...schema.Model) error

DeleteIndex drops the index(es).

type VectorType

type VectorType map[string][]float64

Jump to

Keyboard shortcuts

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