appsearch

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Mar 30, 2021 License: MIT Imports: 10 Imported by: 0

README

appsearch

AppSearch API Client for GoLang (incomplete).

Documentation

Quickstart

package main

import (
	"context"
	"github.com/yurihq/appsearch"
)

func main() {
	client, _ := appsearch.Open("https://[email protected]")

	// Engine will be created if it doesn't exist and schema will be updated
	client.EnsureEngine(ctx, appsearch.CreateEngineRequest{
		Name:     "civilizations",
		Language: "en",
	}, appsearch.SchemaDefinition{
		"name":        "text",
		"rating":      "number",
		"description": "text",
	})

	client.UpdateDocuments(ctx, "civilizations", []map[string]interface{}{
		{"name": "Babylonian", "rating": 5212.2, "description": "Technological and scientific"},
	})

	search, _ := client.SearchDocuments(ctx, "civilizations", appsearch.Query{
		Query: "science",
	})

	println(search.Results[0])

	/*
	{
	  "_meta": {
	    "score": 1396363.1
	  },
	  "name": {
	    "raw": "Babylonian"
	  },
	  "description": {
	    "raw": "Technological and scientific"
	  },
	  "rating": {
	    "raw": 5212.2
	  },
	  "id": {
	    "raw": "park_everglades"
	  }
	}
	*/
}

Implemented API's

Documentation

Index

Constants

View Source
const (
	SchemaTypeText        = "text"
	SchemaTypeDate        = "date"
	SchemaTypeNumber      = "number"
	SchemaTypeGeolocation = "geolocation"
)

Variables

View Source
var (
	ErrInvalidParams       = errors.New("invalid params specified for Open(): accepted are (endpoint, [key])")
	ErrEngineDoesntExist   = errors.New("engine doesn't exist")
	ErrEngineAlreadyExists = errors.New("engine already exists")
)

Functions

func Normalize

func Normalize(raw m, schema SchemaDefinition) (normalizedFlatMap m, err error)

Normalize nested map into flat map as defined in schema Keys are stripped of trailing underscores, lowercased and flattened with underscore (_) separator

func Open

func Open(endpointAndKey ...string) (*client, error)

Open APIClient with endpoint and key First parameter may be specified as URL with API key in authentication like: https://[email protected] Second parameter is always interpreted as API key if specified

Types

type APIClient

type APIClient interface {
	// Engine API
	EngineAPI
	// Schema API
	SchemaAPI
	// Document API
	DocumentAPI
}

APIClient interface

type BoostFunction added in v1.1.0

type BoostFunction = string
const (
	LinearFunction      BoostFunction = "linear"
	GaussianFunction    BoostFunction = "gaussian"
	ExponentialFunction BoostFunction = "exponential"
)

type BoostOperation added in v1.1.0

type BoostOperation = string
const (
	AddOperation      BoostOperation = "add"
	MultiplyOperation BoostOperation = "multiply"
)

type BoostType added in v1.1.0

type BoostType = string
const (
	ValueBoost      BoostType = "value"
	ProximityBoost  BoostType = "proximity"
	FunctionalBoost BoostType = "functional"
)

type CreateEngineRequest added in v1.1.0

type CreateEngineRequest struct {
	Name     string `json:"name"`
	Language string `json:"language,omitempty"`
}

Request for CreateEngine

type DeleteResponse

type DeleteResponse struct {
	// Deleted document ID
	ID string `json:"id"`
	// Was document deleted successfully
	Deleted bool `json:"deleted"`
	// List of errors
	Errors []string `json:"errors"`
}

Response for Patch or Update operations

type DocumentAPI added in v1.1.0

type DocumentAPI interface {
	// Patch a list of documents. Every document must contain "id".
	// Every document is processed separately.
	// Documents without ID will be rejected.
	// Non-existent documents will be rejected.
	PatchDocuments(ctx context.Context, engineName string, documents interface{}) (res []UpdateResponse, err error)
	// Update (replace) a list of documents
	// Every document is processed separately.
	// Documents without ID will have auto-generated ID's.
	// Non-existent documents will be automatically created.
	UpdateDocuments(ctx context.Context, engineName string, documents interface{}) (res []UpdateResponse, err error)
	// Remove a list of documents specified as []string of ID's or []interface{} of documents with "id" field
	// Every document is processed separately.
	RemoveDocuments(ctx context.Context, engineName string, documentsOrIDs interface{}) (res []DeleteResponse, err error)
	// Search documents by query
	SearchDocuments(ctx context.Context, engineName string, query Query) (response SearchResponse, err error)
}

type EngineAPI added in v1.1.0

type EngineAPI interface {
	// List an engine by name
	ListEngine(ctx context.Context, engineName string) (data EngineDescription, err error)
	// List engines with pagination
	ListEngines(ctx context.Context, page Page) (data EngineResponse, err error)
	// List all available engines
	ListAllEngines(ctx context.Context) (data []EngineDescription, err error)

	// Create engine with name
	CreateEngine(ctx context.Context, request CreateEngineRequest) (EngineDescription, error)
	// Delete engine with name
	DeleteEngine(ctx context.Context, engineName string) (err error)

	// Create engine if doesn't exist.
	// Optionally update a schema even if engine exists.
	EnsureEngine(ctx context.Context, request CreateEngineRequest, schema ...SchemaDefinition) (err error)
}

type EngineDescription

type EngineDescription struct {
	Name          string  `json:"name"`
	Type          string  `json:"type"`
	Language      *string `json:"language"`
	DocumentCount int     `json:"document_count"`
}

Engine description

type EngineResponse

type EngineResponse struct {
	Meta    ResponseMeta        `json:"meta"`
	Results []EngineDescription `json:"results"`
}

ListEngines response

type Error

type Error struct {
	Message    string   `json:"error"`
	Messages   []string `json:"errors"`
	StatusCode int      `json:"code"`
}

API Error

func (*Error) Error

func (e *Error) Error() string

type Facet added in v1.1.0

type Facet struct {
	Type   FacetType `json:"type"`
	Name   string    `json:"name"`
	Sort   Sorting   `json:"sort,omitempty"`
	Size   int       `json:"size,omitempty"`
	Ranges []Range   `json:"ranges,omitempty"`
}

type FacetType added in v1.1.0

type FacetType = string
const (
	ValueFacet FacetType = "value"
	RangeFacet FacetType = "range"
)

type FieldWithWeight added in v1.1.0

type FieldWithWeight struct {
	Weight float32 `json:"weight"`
}

type Page

type Page struct {
	Page int `json:"current,omitempty"`
	Size int `json:"size,omitempty"`
}

type PaginationMeta added in v1.1.0

type PaginationMeta struct {
	PageSize     int `json:"size"`
	TotalPages   int `json:"total_pages"`
	CurrentPage  int `json:"current"`
	TotalResults int `json:"total_results"`
}

Pagination metadata included in paged responses

type Query added in v1.1.0

type Query struct {
	// Lucene query
	Query string `json:"query"`
	// Pagination
	Page *Page `json:"page,omitempty"`
	// Sorting
	Sort Sorting `json:"sort,omitempty"`
	// Search grouping
	Group *SearchGroup `json:"group,omitempty"`
	// Search facets
	Facets SearchFacets `json:"facets,omitempty"`
	// Search filters
	Filters SearchFilters `json:"filters,omitempty"`
	// Search boosts
	Boosts SearchBoosts `json:"boosts,omitempty"`
	// Search fields
	SearchFields SearchFields `json:"search_fields,omitempty"`
	// Result fields
	ResultFields ResultFields `json:"result_fields,omitempty"`
	// Analytics
	Analytics *SearchAnalytics `json:"analytics,omitempty"`
}

Search query structure TODO: query builder

type Range added in v1.1.0

type Range struct {
	From interface{} `json:"from"`
	To   interface{} `json:"to"`
}

type RawField added in v1.1.0

type RawField struct {
	Size int `json:"size,omitempty"`
}

type ResponseMeta added in v1.1.0

type ResponseMeta struct {
	Page      PaginationMeta `json:"page"`
	Alerts    []string       `json:"alerts"`
	Warnings  []string       `json:"warnings"`
	RequestID string         `json:"request_id"`
}

Response metadata included in some responses

type ResultField added in v1.1.0

type ResultField struct {
	Raw     *RawField     `json:"raw,omitempty"`
	Snippet *SnippetField `json:"snippet,omitempty"`
}

type ResultFields added in v1.1.0

type ResultFields = map[string]ResultField

type SchemaAPI added in v1.1.0

type SchemaAPI interface {
	// List a schema definition by engineName
	ListSchema(ctx context.Context, engineName string) (data SchemaDefinition, err error)

	// Update schema by engineName (create or change fields).
	// Fields cannot be deleted.
	UpdateSchema(ctx context.Context, engineName string, def SchemaDefinition) (err error)
}

type SchemaDefinition

type SchemaDefinition map[string]SchemaType

Schema definition as map[string]SchemaType "id" field of "text" type is added to schema automatically (non-standard behaviour).

type SchemaType

type SchemaType = string

Schema type defines 4 types of value: text (""), date (time.RFC3339), number (0) and geolocation ("0.0,0.0")

type SearchAnalytics added in v1.1.0

type SearchAnalytics struct {
	Tags []string `json:"tags"`
}

type SearchBoost added in v1.1.0

type SearchBoost struct {
	Type   BoostType   `json:"type"`
	Value  interface{} `json:"value,omitempty"`
	Factor float32     `json:"factor,omitempty"`
	// Operation for ValueBoost or FunctionalBoost
	Operation BoostOperation `json:"operation,omitempty"`
	// Function for FunctionalBoost or ProximityBoost
	Function BoostFunction `json:"function,omitempty"`
	// Center for ProximityBoost
	Center string `json:"center,omitempty"`
}

type SearchBoosts added in v1.1.0

type SearchBoosts = map[string]SearchBoost

type SearchFacets added in v1.1.0

type SearchFacets = map[string][]Facet

type SearchFields added in v1.1.0

type SearchFields = map[string]FieldWithWeight

type SearchFilters added in v1.1.0

type SearchFilters = m

type SearchGroup added in v1.1.0

type SearchGroup struct {
	Field string  `json:"field"`
	Size  int     `json:"size,omitempty"`
	Sort  Sorting `json:"sort,omitempty"`
	// TODO: IDK which type this field must have. Definition is unclear in spec.
	Collapse interface{} `json:"collapse,omitempty"`
}

type SearchResponse added in v1.1.0

type SearchResponse struct {
	Meta    ResponseMeta `json:"meta"`
	Results []m          `json:"results"`
}

Document Search API response

type SnippetField added in v1.1.0

type SnippetField struct {
	Size     int  `json:"size,omitempty"`
	Fallback bool `json:"fallback,omitempty"`
}

type Sorting added in v1.1.0

type Sorting = stringMap

type UpdateResponse

type UpdateResponse struct {
	// Updated document ID
	ID string `json:"id"`
	// List of errors
	Errors []string `json:"errors"`
}

Response for Patch or Update operations

Directories

Path Synopsis
internal
pkg

Jump to

Keyboard shortcuts

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