sajari

package module
v0.0.0-...-e744b49 Latest Latest
Warning

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

Go to latest
Published: Mar 2, 2022 License: MIT Imports: 17 Imported by: 0

README

Search.io SDK for Go

Go reference Build status Report card Sourcegraph

The official Search.io Go client library.

Search.io offers a search and discovery service with Neuralsearch®, the world's first instant AI search technology. Businesses of all sizes use Search.io to build site search and discovery solutions that maximize e-commerce revenue, optimize on-site customer experience, and scale their online presence.

Table of contents

Requirements

Requires Go version 1.13 or higher.

Installation

Install sdk-go with:

go get -u code.sajari.com/sdk-go

Then, import it using:

import "code.sajari.com/sdk-go"

Documentation

Below are a few simple examples that will help get you up and running.

Creating a client

To start you need to create a client to make calls to the API.

You can get your account ID, collection ID, key ID and key secret from the Search.io console.

creds := sajari.KeyCredentials("key-id", "key-secret")
client, err := sajari.New("account_id", "collection_id", sajari.WithCredentials(creds))
if err != nil {
	// handle
}
defer client.Close()

Note: do not forget to close the client when you are finished with it.

Overriding the default endpoint

If you need to override the default endpoint, you can use the WithEndpoint client option.

opts := []sajari.Opt{
	sajari.WithEndpoint("api-au-valkyrie.sajari.com:50051"),
	sajari.WithCredentials(sajari.KeyCredentials("key-id", "key-secret")),
}

client, err := sajari.New(shop.AccountID, shop.CollectionID, opts...)
if err != nil {
	// handle
}
defer client.Close()
Available endpoints

The endpoints that you can pass to WithEndpoint include:

  • api-au-valkyrie.sajari.com:50051
  • api-us-valkyrie.sajari.com:50051
Adding a record

A record can be added to a collection using the CreateRecord method on a record Pipeline.

First, you should initialise the record pipeline by passing in its name and the version you want to use.

pipeline := client.Pipeline("record", "v5")

Next, set up any values that you need to pass to the record pipeline, define your record and call CreateRecord.

Values allow you to control the pipeline execution. For example, they can be used to dynamically turn pipeline steps on or off and control how the record is processed.

values := map[string]string{
	// ...
}

record := sajari.Record{
	"id":    12345,
	"name":  "Smart TV",
	"brand": "Sunny",
	"price": 999,
}

key, _, err := pipeline.CreateRecord(context.Background(), values, record)
if err != nil {
	// handle
}

You can use the returned key to uniquely identify the newly inserted record. This can be used in various calls such as GetRecord, MutateRecord, DeleteRecord and ReplaceRecord.

Getting a record

An existing record in your collection can be retrieved using the GetRecord method on your Client.

key := sajari.NewKey("id", "12345") // or using your Key returned from another call
record, err := client.GetRecord(context.Background(), key)
if err != nil {
	// handle
}
Replacing a record

An existing record in your collection can be entirely replaced using the ReplaceRecord method on a record Pipeline.

When calling ReplaceRecord Search.io actually performs an upsert. If the record is an existing record, Search.io performs a diff between the old and new records and applies your changes—this is extremely efficient. Because ReplaceRecord can both insert and update it is typically preferred over CreateRecord when adding a record.

Note: if you want to make granular changes to the record it is best to use MutateRecord.

Note: if you want to change an indexed field you will need to use ReplaceRecord.

First, you should initialise the record pipeline by passing in its name and the version you want to use.

pipeline := client.Pipeline("record", "v5")

Next, set up any values that you need to pass to the record pipeline, define your record and call ReplaceRecord.

Values allow you to control the pipeline execution. For example, they can be used to dynamically turn pipeline steps on or off and control how the record is processed.

values := map[string]string{
	// ...
}

key := sajari.NewKey("id", "12345") // or using your Key returned from another call

record := sajari.Record{
	"id":    12345,
	"name":  "Large Smart TV",
	"brand": "Sunny",
	"price": 999,
}

key, _, err = pipeline.ReplaceRecord(context.Background(), values, key, record)
if err != nil {
	// handle
}
Mutating a record

An existing record in your collection can be mutated using the MutateRecord method on your Client. You might need this method if you need to update a single field or unset a single field.

As an example, if you were storing products in your collection and you needed to update a product's price or stock levels this method would be useful.

Note: if you want to replace the entire record it is best to use ReplaceRecord.

Note: if you want to change an indexed field you will need to use ReplaceRecord.

You will need to pass one or more mutation operations to MutateRecord that will be appled to your record. For example, you can pass an operation to set a field, unset a field or set multiple fields at once.

key := sajari.NewKey("id", "12345") // or using your Key returned from another call

// update a single field
err := client.MutateRecord(context.Background(), key, sajari.SetFieldValue("updated_at", time.Now().String()))
if err != nil {
	// handle
}

// unset a single field
err := client.MutateRecord(context.Background(), key, sajari.SetFieldValue("available", nil))
if err != nil {
	// handle
}

// set multiple fields at once
err := client.MutateRecord(context.Background(), key, sajari.SetFields(map[string]interface{}{
	"updated_at": time.Now().String(),
	"available":  nil,
})...)
if err != nil {
	// handle
}
Deleting a record

An existing record in your collection can be deleted using the DeleteRecord method on your Client.

key := sajari.NewKey("id", "12345") // or using your Key returned from another call
err := client.DeleteRecord(context.Background(), key)
if err != nil {
	// handle
}
Searching for records

You can search for records in your collection using the Search method with a query Pipeline.

First, you should initialise the query pipeline by passing in its name and the version you want to use.

pipeline := client.Pipeline("search", "v5")

Next, set up any values that you need to pass to the query pipeline, create a session and run your search.

Values allow you to control the pipeline execution. For example, they can be used to dynamically turn pipeline steps on or off and control how the records are processed.

In the example below, passing the resultsPerPage and page values allows you to paginate through records for the search query provided in q. Note: this assumes that you have the pagination step in your query pipeline.

values := map[string]string{
	"q":              "your search terms",
	"resultsPerPage": "10",
	"page":           "1",
}

res, _, err := pipeline.Search(context.Background(), values, sajari.NonTrackedSession())
if err != nil {
	// handle
}

for _, r := range res.Results {
	log.Printf("Values: %v", r.Values)
	log.Printf("Tokens: %v", r.Tokens)
}
Tracking

If you don't want tracking enabled, then use NonTrackedSession. For example your Search call might look like:

res, _, err := pipeline.Search(context.Background(), values, sajari.NonTrackedSession())
if err != nil {
	// handle
}

If you're tracking website-style searches, then use WebSearchSession. For example your Search call might look like:

res, _, err := pipeline.Search(context.Background(), values, sajari.WebSearchSession("q", sajari.NewSession()))
if err != nil {
	// handle
}

If you want to manage the details of tracking externally, use Tracking. For example your Search call might look like:

res, _, err := pipeline.Search(context.Background(), values, sajari.Tracking{
	Type:     sajari.TrackingPosNeg,
	QueryID:  "4216691599",
	Sequence: 1,
	Field:    "id",
	Data:     map[string]string{},
})
if err != nil {
	// handle
}

Development

Pull requests from the community are welcome. If you submit one, please keep the following guidelines in mind:

  1. Code must be go fmt compliant.
  2. All types, structs and funcs should be documented.
  3. Ensure that go test ./... succeeds.

Test

Run all tests:

go test ./...

License

We use the MIT License.

Documentation

Overview

Package sajari provides functionality for interacting with Search.io APIs.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrNoSuchCollection is returned when a collection was requested but there
	// is no such collection.
	ErrNoSuchCollection = errors.New("no such collection")

	// ErrNoSuchCollectionDefaultPipeline is returned when a collection default
	// pipeline was requested but there is no such default.
	ErrNoSuchCollectionDefaultPipeline = errors.New("no such collection default pipeline")
)
View Source
var ErrDone = errors.New("done")

ErrDone is returned when the iteration is complete.

View Source
var ErrNoSuchRecord = errors.New("no such record")

ErrNoSuchRecord is returned when a record was requested but there is no such record.

View Source
var NewSendEventRequest = openapi.NewSendEventRequest

Functions

This section is empty.

Types

type AggregateResult

type AggregateResult interface {
	// contains filtered or unexported methods
}

AggregateResult is an interface implemented by aggregate results.

type BucketResult

type BucketResult struct {
	// Name of the bucket.
	Name string

	// Number of records.
	Count int
}

BucketResult is bucket information as reported by an aggregate.

type BucketsResult

type BucketsResult map[string]BucketResult

BucketsResult is a type returned from a query performing bucket aggregate.

type Client

type Client struct {
	Project    string
	Collection string

	ClientConn *grpc.ClientConn
	// contains filtered or unexported fields
}

Client is a type which makes requests to Search.io.

func New

func New(accountID, collectionID string, opts ...Opt) (*Client, error)

New creates a new Client which can be used to make requests to Search.io services.

Example
package main

import (
	sajari "code.sajari.com/sdk-go"
)

func main() {
	creds := sajari.KeyCredentials("key-id", "key-secret")
	client, err := sajari.New("account_id", "collection_id", sajari.WithCredentials(creds))
	if err != nil {
		// handle
	}
	defer client.Close()
}
Output:

func (*Client) Close

func (c *Client) Close() error

Close releases all resources held by the Client.

func (*Client) DeleteCollection

func (c *Client) DeleteCollection(ctx context.Context, id string) error

DeleteCollection removes a collection identified by the provided ID.

If there is no such collection matching the given ID this method returns an error wrapping ErrNoSuchCollection.

func (*Client) DeleteRecord

func (c *Client) DeleteRecord(ctx context.Context, k *Key) error

DeleteRecord removes a record identified by the key k. Returns non-nil error if there was a communication problem, but fails silently if any key doesn't have a corresponding record.

If there is no such record matching the given key this method returns an error wrapping ErrNoSuchRecord.

Example
package main

import (
	"context"

	sajari "code.sajari.com/sdk-go"
)

func main() {
	creds := sajari.KeyCredentials("key-id", "key-secret")
	client, err := sajari.New("account_id", "collection_id", sajari.WithCredentials(creds))
	if err != nil {
		// handle
	}
	defer client.Close()

	key := sajari.NewKey("id", "12345") // or using your Key returned from another call

	err = client.DeleteRecord(context.Background(), key)
	if err != nil {
		// handle
	}
}
Output:

func (*Client) GetCollection

func (c *Client) GetCollection(ctx context.Context, id string) (*Collection, error)

GetCollection gets a collection identified by the provided ID.

If there is no such collection matching the given ID this method returns an error wrapping ErrNoSuchCollection.

func (*Client) GetDefaultPipeline

func (c *Client) GetDefaultPipeline(ctx context.Context, id string, typ PipelineType) (string, error)

GetDefaultPipeline gets the default pipeline for a collection.

func (*Client) GetRecord

func (c *Client) GetRecord(ctx context.Context, k *Key) (Record, error)

GetRecord retrieves the record identified by the key k.

If there is no such record matching the given key this method returns an error wrapping ErrNoSuchRecord.

Example
package main

import (
	"context"

	sajari "code.sajari.com/sdk-go"
)

func main() {
	creds := sajari.KeyCredentials("key-id", "key-secret")
	client, err := sajari.New("account_id", "collection_id", sajari.WithCredentials(creds))
	if err != nil {
		// handle
	}
	defer client.Close()

	key := sajari.NewKey("id", "12345") // or using your Key returned from another call

	record, err := client.GetRecord(context.Background(), key)
	if err != nil {
		// handle
	}
	_ = record // use record
}
Output:

Example (ErrNoSuchRecord)
package main

import (
	"context"
	"errors"

	sajari "code.sajari.com/sdk-go"
)

func main() {
	creds := sajari.KeyCredentials("key-id", "key-secret")
	client, err := sajari.New("account_id", "collection_id", sajari.WithCredentials(creds))
	if err != nil {
		// handle
	}
	defer client.Close()

	key := sajari.NewKey("id", "12345") // or using your Key returned from another call

	_, err = client.GetRecord(context.Background(), key)
	if err != nil {
		if errors.Is(err, sajari.ErrNoSuchRecord) {
			// handle case where there is no such record
		}
		// handle other error cases
	}
}
Output:

func (*Client) Interaction

func (c *Client) Interaction() *Interaction

Interaction creates a new Interaction which can be used to register interactions.

func (*Client) Keys

func (c *Client) Keys(ctx context.Context, field string) *KeyIterator

Keys returns an iterator which will retrieve the given key field value for each record in the collection. If changes to the collection are made whilst iterating, the iterator may become invalid or return keys already visited.

func (*Client) MutateRecord

func (c *Client) MutateRecord(ctx context.Context, k *Key, fms ...RecordMutation) error

MutateRecord mutates a record identified by the key k by applying the given record mutation operations.

If there is no such record matching the given key this method returns an error wrapping ErrNoSuchRecord.

Example
package main

import (
	"context"
	"time"

	sajari "code.sajari.com/sdk-go"
)

func main() {
	creds := sajari.KeyCredentials("key-id", "key-secret")
	client, err := sajari.New("account_id", "collection_id", sajari.WithCredentials(creds))
	if err != nil {
		// handle
	}
	defer client.Close()

	key := sajari.NewKey("id", "12345") // or using your Key returned from another call

	// update a single field
	err = client.MutateRecord(context.Background(), key, sajari.SetFieldValue("updated_at", time.Now().String()))
	if err != nil {
		// handle
	}

	// unset a single field
	err = client.MutateRecord(context.Background(), key, sajari.SetFieldValue("available", nil))
	if err != nil {
		// handle
	}

	// set multiple fields at once
	err = client.MutateRecord(context.Background(), key, sajari.SetFields(map[string]interface{}{
		"updated_at": time.Now().String(),
		"available":  nil,
	})...)
	if err != nil {
		// handle
	}
}
Output:

func (*Client) Pipeline

func (c *Client) Pipeline(name, version string) *Pipeline

Pipeline returns a Pipeline for querying a collection.

func (*Client) Schema

func (c *Client) Schema() *Schema

Schema returns the schema (list of fields) for the collection.

func (*Client) SendEvent

func (c *Client) SendEvent(ctx context.Context, r *SendEventRequest) error

SendEvent sends an event to the ranking system after a user interacts with a search result.

func (*Client) UpdateCollection

func (c *Client) UpdateCollection(ctx context.Context, id string, opts ...UpdateCollectionOpt) error

UpdateCollection updates a collection identified by the provided ID.

If there is no such collection matching the given ID this method returns an error wrapping ErrNoSuchCollection.

type Collection

type Collection = openapi.Collection

A Collection stores the records that can be searched.

type CountResult

type CountResult map[string]int

CountResult is a type returned from a query which has performed a count aggregate.

type Credentials

type Credentials interface {
	// contains filtered or unexported methods
}

Credentials is an interface which is implemented by types providing credential information used in requests.

func KeyCredentials

func KeyCredentials(keyID, keySecret string) Credentials

KeyCredentials defines a Credential which uses a Key ID-Secret pair.

type DateResult

type DateResult map[string]int

DateResult is a type returned from a query which has performed a date aggregate.

type Field

type Field struct {
	// Name used to identify the field.
	Name string

	// Description of the field.
	Description string

	// Type of the field.
	Type FieldType

	// Mode of the field.
	Mode FieldMode

	// Repeated indicates that this field can hold a list of values.
	Repeated bool

	// Indexes is a list of the field's indexes.
	Indexes []FieldIndex
}

Field represents a meta field which can be assigned in a collection record.

func (Field) Index

func (f Field) Index(spec string) (FieldIndex, bool)

Index returns the index matching the given identifier/specification. If no such index exists then it will return ({}, false).

type FieldIndex

type FieldIndex struct {
	// Spec is the identifier/specification for the creation of the index.
	Spec string
	// Description is a description of the index.
	Description string
}

FieldIndex is a field index.

type FieldIterator

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

FieldIterator iterates through a list of fields.

func (*FieldIterator) Next

func (it *FieldIterator) Next() (Field, error)

Next returns the next field in the iteration. If there are no more fields remaining then an error wrapping ErrDone is returned.

type FieldMode

type FieldMode string

FieldMode defines field modes.

const (
	ModeNullable FieldMode = "NULLABLE" // Don't require a value.
	ModeRequired FieldMode = "REQUIRED" // Field value must be set.
	ModeUnique   FieldMode = "UNIQUE"   // Field value must be unique (and hence also set).
)

Enumeration of field modes.

type FieldMutation

type FieldMutation interface {
	// contains filtered or unexported methods
}

FieldMutation is an interface which is satisfied by schema field mutations.

func FieldAddIndexMutation

func FieldAddIndexMutation(x FieldIndex) FieldMutation

FieldAddIndexMutation adds a schema field mutation which adds an index to a field.

func FieldModeMutation

func FieldModeMutation(m FieldMode) FieldMutation

FieldModeMutation creates a schema field mutation which changes the unique constraint on a field.

func FieldNameMutation

func FieldNameMutation(name string) FieldMutation

FieldNameMutation creates a schema field mutation which changes the name of a field.

func FieldRepeatedMutation

func FieldRepeatedMutation(repeated bool) FieldMutation

FieldRepeatedMutation creates a schema field mutation which changes the repeated property on a field.

func FieldTypeMutation

func FieldTypeMutation(ty FieldType) FieldMutation

FieldTypeMutation creates a schema field mutation which changes the type of a field.

type FieldType

type FieldType string

FieldType defines field data types.

const (
	TypeString    FieldType = "STRING"
	TypeInteger   FieldType = "INTEGER"
	TypeFloat     FieldType = "FLOAT"
	TypeDouble    FieldType = "DOUBLE"
	TypeBoolean   FieldType = "BOOLEAN"
	TypeTimestamp FieldType = "TIMESTAMP"
)

Enumeration of field types.

type Interaction

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

Interaction is used to register interactions.

func (*Interaction) ConsumeToken

func (i *Interaction) ConsumeToken(ctx context.Context, token string, options InteractionOptions) error

ConsumeToken registers an interaction corresponding to a token.

type InteractionOptions

type InteractionOptions struct {
	Identifier string
	Weight     int32
	Data       map[string]string
}

InteractionOptions are passed with the token.

type Key

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

Key is a unique identifier record.

func NewKey

func NewKey(field string, value interface{}) *Key

NewKey creates a new key with a field and value. Field must be marked as unique in the collection schema.

func (*Key) Field

func (k *Key) Field() string

Field returns the key's field.

func (*Key) String

func (k *Key) String() string

String implements Stringer.

func (*Key) Value

func (k *Key) Value() interface{}

Value returns the key's value.

type KeyIterator

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

KeyIterator iterates through a list of keys.

func (*KeyIterator) Next

func (it *KeyIterator) Next() (*Key, error)

Next returns the next key in the iteration. If there are no more keys remaining then an error wrapping ErrDone is returned.

type NoDefaultPipelineError

type NoDefaultPipelineError struct {
	// Name of the pipeline used in the attempted operation.
	Name string
}

NoDefaultPipelineError is the error type returned when the collection does not have a default version set for a given pipeline. To resolve errors of this type, the caller should either pass an explicit pipeline version along with their pipeline name, or they should set a default pipeline version using the API or CLI tools.

func (*NoDefaultPipelineError) Error

func (e *NoDefaultPipelineError) Error() string

Error implements error.

type Opt

type Opt func(c *Client)

Opt is a type which defines Client options.

func WithCredentials

func WithCredentials(cr Credentials) Opt

WithCredentials sets the client credentials used in each request.

func WithEndpoint

func WithEndpoint(endpoint string) Opt

WithEndpoint configures the client to use a custom endpoint.

func WithGRPCDialOption

func WithGRPCDialOption(opt grpc.DialOption) Opt

WithGRPCDialOption returns an Opt which appends a new grpc.DialOption to an underlying gRPC dial.

func WithV4Endpoint

func WithV4Endpoint(endpoint string) Opt

WithV4Endpoint configures the client to use a v4 endpoint.

type Pipeline

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

Pipeline is a handler for a named pipeline.

func (*Pipeline) CreateRecord

func (p *Pipeline) CreateRecord(ctx context.Context, values map[string]string, r Record) (*Key, map[string]string, error)

CreateRecord uses a pipeline to add a single record to a collection and returns a Key which can be used to retrieve the newly created record.

Example
package main

import (
	"context"

	sajari "code.sajari.com/sdk-go"
)

func main() {
	creds := sajari.KeyCredentials("key-id", "key-secret")
	client, err := sajari.New("account_id", "collection_id", sajari.WithCredentials(creds))
	if err != nil {
		// handle
	}
	defer client.Close()

	pipeline := client.Pipeline("record", "v5")

	values := map[string]string{
		// ...
	}

	record := sajari.Record{
		"id":    12345,
		"name":  "Smart TV",
		"brand": "Sunny",
		"price": 999,
	}

	key, _, err := pipeline.CreateRecord(context.Background(), values, record)
	if err != nil {
		// handle
	}
	_ = key // use key
}
Output:

func (*Pipeline) ReplaceRecord

func (p *Pipeline) ReplaceRecord(ctx context.Context, values map[string]string, key *Key, r Record) (*Key, map[string]string, error)

ReplaceRecord uses a pipeline to replace a single record in a collection represented by the given Key.

Example
package main

import (
	"context"

	sajari "code.sajari.com/sdk-go"
)

func main() {
	creds := sajari.KeyCredentials("key-id", "key-secret")
	client, err := sajari.New("account_id", "collection_id", sajari.WithCredentials(creds))
	if err != nil {
		// handle
	}
	defer client.Close()

	pipeline := client.Pipeline("record", "v5")

	values := map[string]string{
		// ...
	}

	key := sajari.NewKey("id", "12345") // or using your Key returned from another call

	record := sajari.Record{
		"id":    12345,
		"name":  "Smart TV",
		"brand": "Sunny",
		"price": 899,
	}

	key, _, err = pipeline.ReplaceRecord(context.Background(), values, key, record)
	if err != nil {
		// handle
	}
	_ = key // use key
}
Output:

func (*Pipeline) Search

func (p *Pipeline) Search(ctx context.Context, params map[string]string, s Session) (*Results, map[string]string, error)

Search runs a search query defined by a pipeline with the given params and session to run in. Returns the query results and returned params (which could have been modified in the pipeline).

Example
package main

import (
	"context"
	"log"

	sajari "code.sajari.com/sdk-go"
)

func main() {
	creds := sajari.KeyCredentials("key-id", "key-secret")
	client, err := sajari.New("account_id", "collection_id", sajari.WithCredentials(creds))
	if err != nil {
		// handle
	}
	defer client.Close()

	pipeline := client.Pipeline("query", "v5")

	values := map[string]string{
		"q":              "your search terms",
		"resultsPerPage": "10",
		"page":           "1",
	}

	res, _, err := pipeline.Search(context.Background(), values, sajari.NonTrackedSession())
	if err != nil {
		// handle
	}

	for _, r := range res.Results {
		log.Printf("Values: %v", r.Values)
		log.Printf("Tokens: %v", r.Tokens)
	}
}
Output:

Example (NoDefaultPipelineError)
package main

import (
	"context"
	"errors"

	sajari "code.sajari.com/sdk-go"
)

func main() {
	creds := sajari.KeyCredentials("key-id", "key-secret")
	client, err := sajari.New("account_id", "collection_id", sajari.WithCredentials(creds))
	if err != nil {
		// handle
	}
	defer client.Close()

	pipeline := client.Pipeline("query", "")

	values := map[string]string{
		"q": "your search terms",
	}

	_, _, err = pipeline.Search(context.Background(), values, sajari.NonTrackedSession())
	if err != nil {
		var e *sajari.NoDefaultPipelineError
		if errors.As(err, &e) {
			// handle case where there is no default pipeline version set
		}
		// handle other error cases
	}
}
Output:

type PipelineType

type PipelineType string

PipelineType represents the type of a pipeline.

const (
	// RecordPipelineType is the record pipeline type.
	RecordPipelineType PipelineType = "RECORD"
	// QueryPipelineType is the query pipeline type.
	QueryPipelineType PipelineType = "QUERY"
)

type Record

type Record map[string]interface{}

Record is a set of field-value pairs representing a record in a collection.

type RecordMutation

type RecordMutation interface {
	// contains filtered or unexported methods
}

RecordMutation is an interface satisfied by all record mutations defined in this package.

func SetFieldValue

func SetFieldValue(field string, value interface{}) RecordMutation

SetFieldValue is a RecordMutation which sets field to value. If value is nil then this unsets field.

func SetFields

func SetFields(m map[string]interface{}) []RecordMutation

SetFields is a convenience method for creating field mutations to set a map of values.

type Result

type Result struct {
	// Values are field values of records.
	Values map[string]interface{}

	// Tokens contains any tokens associated with this Result.
	Tokens map[string]interface{}

	// Score is the overall score of this Result.
	Score float64

	// IndexScore is the index-matched score of this Result.
	IndexScore float64
}

Result is an individual query result.

type Results

type Results struct {
	// Reads is the total number of index values read.
	Reads int

	// TotalResults is the total number of results for the query.
	TotalResults int

	// Time taken to perform the query.
	Latency time.Duration

	// Aggregates computed on the query results (see Aggregate).
	Aggregates map[string]interface{}

	// AggregateFilters computed on query results (see Aggregate).
	AggregateFilters map[string]interface{}

	// Results of the query.
	Results []Result
}

Results is a collection of results from a Search.

type Schema

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

Schema provides methods for managing collection schemas. Use Client.Schema to create one for a collection.

func (*Schema) CreateField

func (s *Schema) CreateField(ctx context.Context, f Field) error

CreateField creates a new field in the schema.

func (*Schema) Fields

func (s *Schema) Fields(ctx context.Context) *FieldIterator

Fields returns an iterator which retrieves all the fields in the collection.

func (*Schema) MutateField

func (s *Schema) MutateField(ctx context.Context, name string, m FieldMutation) error

MutateField mutates the field identified by name.

type SendEventRequest

type SendEventRequest = openapi.SendEventRequest

type Session

type Session interface {
	// Reset the session.
	Reset()
	// contains filtered or unexported methods
}

Session is an interface which defines session handling for search.

func NewSession

func NewSession(ty TrackingType, field string, data map[string]string) Session

NewSession creates a Session which generates tracking information for performing queries within a search.

func NonTrackedSession

func NonTrackedSession() Session

NonTrackedSession creates a session with no tracking enabled.

func WebSearchSession

func WebSearchSession(queryLabel string, s Session) Session

WebSearchSession handles search sessions for website-style searching.

It tracks the search text (pass to the query pipeline via queryLabel), and determines if the session should be reset (i.e. if the query text has changed significantly).

A common session handler would be:

WebSearchSession("q", NewSession())

type Tracking

type Tracking struct {
	Type TrackingType

	// Query ID of the query.
	QueryID string

	// Sequence number of query.
	Sequence int

	// Tracking field used to identify records in the collection.
	// Must be unique schema field.
	Field string

	// Custom values to be included in tracking data.
	Data map[string]string
}

Tracking provides a Session implementation where the details of the tracking object are managed by an external source.

Example
package main

import (
	"context"

	sajari "code.sajari.com/sdk-go"
)

func main() {
	creds := sajari.KeyCredentials("key-id", "key-secret")
	client, err := sajari.New("account_id", "collection_id", sajari.WithCredentials(creds))
	if err != nil {
		// handle
	}
	defer client.Close()

	pipeline := client.Pipeline("query", "")

	values := map[string]string{
		"q": "your search terms",
	}

	_, _, err = pipeline.Search(context.Background(), values, &sajari.Tracking{
		Type:     sajari.TrackingPosNeg,
		QueryID:  "4216691599",
		Sequence: 1,
		Field:    "id",
		Data:     map[string]string{},
	})
	if err != nil {
		// handle
	}
}
Output:

func (*Tracking) Reset

func (t *Tracking) Reset()

type TrackingType

type TrackingType string

TrackingType defines different modes of tracking which can be applied to query requests.

const (
	TrackingNone   TrackingType = ""        // No tracking is enabled.
	TrackingClick  TrackingType = "CLICK"   // Click tracking is enabled, Click tokens will be returned with results.
	TrackingPosNeg TrackingType = "POS_NEG" // Positive/negative interaction tokens should be returned with results.
)

TrackingType constants.

type UpdateCollectionOpt

type UpdateCollectionOpt func(c *openapi.Collection, updateMask map[string]struct{})

UpdateCollectionOpt is a type which defines options to update a collection.

func SetAuthorizedQueryDomains

func SetAuthorizedQueryDomains(domains []string) UpdateCollectionOpt

SetAuthorizedQueryDomains is a collection mutation that set a collection's authorized query domains.

func SetCollectionDisplayName

func SetCollectionDisplayName(displayName string) UpdateCollectionOpt

SetCollectionDisplayName is a collection mutation that set a collection's display name.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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