meilisearch

package module
v0.8.4 Latest Latest
Warning

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

Go to latest
Published: Feb 5, 2020 License: MIT Imports: 10 Imported by: 254

README

GitHub Workflow Status Go Report Card

Description

This Go library is a client for the MeiliSearch Database.

Currently the whole API is not yet implemented.

Warning: WIP this is not yet usable in production.

Dependencies

  • github.com/pkg/errors for error wrapping

How to use it

package main

import (
    "github.com/alexisvisco/meilisearch-go"
    "fmt"
)

func main() {

    // meilisearch package will maybe be renamed into ms ?

    client := meilisearch.NewClient(meilisearch.Config{
        Host: "http://localhost:7700",
    })
    
    index, err := client.Indexes().Create(meilisearch.CreateIndexRequest{
        Name: "Meilimelo",
        Schema: meilisearch.Schema{
            "id": {
                meilisearch.SchemaAttributesIdentifier,
                meilisearch.SchemaAttributesIndexed, 
                meilisearch.SchemaAttributesDisplayed, 
            },
        },
    })
    
    // advanced error handling  err.(*meilisearch.Error)
    // do stuff with index and err
    
    if err != nil {
        panic(err)
    }
    
    fmt.Println(index)
}

Stable part of this library

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ACL

type ACL string
const (
	AclIndexesRead    ACL = "indexesRead"
	AclIndexesWrite   ACL = "indexesWrite"
	AclDocumentsRead  ACL = "documentsRead"
	AclDocumentsWrite ACL = "documentsWrite"
	AclSettingsRead   ACL = "settingsRead"
	AclSettingsWrite  ACL = "settingsWrite"
	AclAdmin          ACL = "admin"
	AclAll            ACL = "all"
)

type APIKey

type APIKey struct {
	Key         string    `json:"key"`
	Description string    `json:"description"`
	Acl         []ACL     `json:"acl"`
	Indexes     []string  `json:"indexes"`
	CreatedAt   time.Time `json:"createdAt"`
	UpdatedAt   time.Time `json:"updatedAt"`
	ExpiresAt   time.Time `json:"expiresAt"`
	Revoked     bool      `json:"revoked"`
}

type ApiDocuments

type ApiDocuments interface {

	// Get one document using its unique identifier.
	// documentPtr should be a pointer.
	Get(identifier string, documentPtr interface{}) error

	// Delete one document based on its unique identifier.
	Delete(identifier string) (*AsyncUpdateId, error)

	// Delete a selection of documents based on array of identifiers.
	Deletes(identifier []string) (*AsyncUpdateId, error)

	// List the documents in an unordered way.
	// WARNING: this route is a non-optimized route, it can be a little bit slow to answer.
	List(request ListDocumentsRequest, documentsPtr interface{}) error

	// AddOrUpdate a list of documents, update them if they already exist based on their unique identifiers.
	AddOrUpdate(documentsPtr interface{}) (*AsyncUpdateId, error)

	// DeleteAllDocuments in the specified index.
	DeleteAllDocuments() (*AsyncUpdateId, error)

	ApiWithIndexID
}

ApiDocuments are objects composed of fields containing any data.

Documentation: https://docs.meilisearch.com/references/documents.html

type ApiHealth

type ApiHealth interface {

	// Get health of MeiliSearch server.
	Get() error

	// Update health of MeiliSearch server.
	Set(health bool) error
}

ApiHealth handle health of a MeiliSearch server.

Documentation: https://docs.meilisearch.com/references/health.html

type ApiIndexes

type ApiIndexes interface {

	// Get the index relative information.
	Get(uid string) (*Index, error)

	// List all indexes.
	List() ([]Index, error)

	// Create an index.
	// The schema definition is optionally send through the body. If no schema has been defined when the first document
	// is sent it will be inferred based on that document.
	// If no UID is specified in the request a randomly generated UID will be returned.
	// It's associated to the new index. This UID will be essential to make all request over the created index.
	Create(request CreateIndexRequest) (*CreateIndexResponse, error)

	// Update an index name.
	Update(uid string, name string) (*Index, error)

	// Delete an index.
	Delete(uid string) (bool, error)

	// GetRawSchema get the schema of one index using the RawSchema type.
	GetRawSchema(uid string) (*RawSchema, error)

	// GetSchema get the schema of one index using the Schema type.
	GetSchema(uid string) (*Schema, error)

	// UpdateSchema an index schema by using the Schema type.
	UpdateSchema(uid string, schema Schema) (*AsyncUpdateId, error)

	// UpdateWithRawSchema an index schema by using the RawSchema type.
	UpdateWithRawSchema(uid string, schema RawSchema) (*AsyncUpdateId, error)
}

ApiIndexes, index is an entity, like a table in SQL, with a specific schema definition. It gathers a collection of documents with the structure defined by the schema. An index is defined by an unique identifier uid that is generated by MeiliSearch (if none is given) on index creation. It also has a name to help you track your different indexes.

Documentation: https://docs.meilisearch.com/references/indexes.html

type ApiKeys

type ApiKeys interface {

	// Get information for a given API key.
	Get(key string) (*APIKey, error)

	// Get all API keys information.
	List() ([]APIKey, error)

	// Create an API key.
	Create(request CreateApiKeyRequest) (*APIKey, error)

	// Update an API key.
	Update(key string, request UpdateApiKeyRequest) (*APIKey, error)

	// Delete an API key.
	Delete(key string) (deleted bool, err error)
}

ApiKeys, To communicate with MeiliSearch's RESTfull API most of the routes require an API key.

Documentation: https://docs.meilisearch.com/references/keys.html

type ApiSearch

type ApiSearch interface {

	// Search for documents matching a specific query in the given index.
	Search(params SearchRequest) (*SearchResponse, error)

	ApiWithIndexID
}

Search through documents list in an index.

Documentation: https://docs.meilisearch.com/references/search.html

type ApiSettings

type ApiSettings interface {
	Get() (*Settings, error)
	AddOrUpdate(request Settings) (*AsyncUpdateId, error)
}

type ApiStats

type ApiStats interface {

	// Get stats of an index.
	Get(indexId string) (*Stats, error)

	// Get stats of all indexes.
	List() ([]Stats, error)
}

ApiStats retrieve statistic over all indexes or a specific index id.

Documentation: https://docs.meilisearch.com/references/stats.html

type ApiStopWords

type ApiStopWords interface {

	// List of the stop-words.
	List() ([]string, error)

	// Add stop-words to the list.
	Add(words []string) (*AsyncUpdateId, error)

	// Deletes a list of stop-words from the list.
	Deletes(words []string) (*AsyncUpdateId, error)

	ApiWithIndexID
}

ApiStopWords, stop-words words allow you to ignore certain words in the relevance of your search.

During a search, if your query contains words that you have put in stop-words, they will be ignored by the algorithm that defines the relevance of each document. This increases the speed of the search.

Using stop-words allows the relevance of the search to be focused on more interesting elements such as ranking rather than on the accuracy of the sequence with another one.

Documentation: https://docs.meilisearch.com/references/stop_words.html

type ApiSynonyms

type ApiSynonyms interface {
	List(word string) ([]string, error)
	ListAll() ([]ListSynonymsResponse, error)
	Create(word string, synonyms []string) (*AsyncUpdateId, error)
	Update(word string, synonyms []string) (*AsyncUpdateId, error)
	Delete(word string) (*AsyncUpdateId, error)
	BatchCreate(request BatchCreateSynonymsRequest) (*AsyncUpdateId, error)
	DeleteAll() (*AsyncUpdateId, error)

	ApiWithIndexID
}

type ApiSystemInformation

type ApiSystemInformation interface {
	Get() (*SystemInformation, error)
	GetPretty() (*SystemInformationPretty, error)
}

type ApiUpdates

type ApiUpdates interface {

	// Get the status of an update in a given index.
	Get(id int64) (*Update, error)

	// Get the status of all updates in a given index.
	List() ([]Update, error)
}

ApiUpdates, MeiliSearch is an asynchronous API. It means that the API does not behave as you would typically expect when handling the request's responses.

Some actions are put in a queue and will be executed in turn (asynchronously). In this case, the server response contains the identifier to track the execution of the action.

This API permit to get the state of an update id.

Documentation: https://docs.meilisearch.com/references/updates.html

type ApiVersion

type ApiVersion interface {

	// Get version of MeiliSearch.
	Get() (*Version, error)
}

ApiVersion retrieve the version of MeiliSearch.

Documentation: https://docs.meilisearch.com/references/version.html

type ApiWithIndexID

type ApiWithIndexID interface {
	IndexId() string
	Client() *Client
}

ApiWithIndexID is used to await an async update id response. Each apis that use an index internally implement this interface except ApiUpdates.

type AsyncUpdateId

type AsyncUpdateId struct {
	UpdateID int64 `json:"updateId"`
}

type Attributes

type Attributes map[string]bool

type BatchCreateSynonymsRequest

type BatchCreateSynonymsRequest []Synonym

type Client

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

Client is a structure that give you the power for interacting with an high-level api with meilisearch.

func NewClient

func NewClient(config Config) *Client

NewClient create a Client from a Config structure.

func NewClientWithCustomHttpClient

func NewClientWithCustomHttpClient(config Config, client http.Client) *Client

NewClientWithCustomHttpClient create a Client from a Config structure and a http.Client which you can customize.

func (Client) AwaitAsyncUpdateId

func (c Client) AwaitAsyncUpdateId(indexId string, updateId *AsyncUpdateId) UpdateStatus

AwaitAsyncUpdateId check each 16ms the status of a AsyncUpdateId. This method should be avoided. TODO: improve this method by returning a channel

func (*Client) Documents

func (c *Client) Documents(indexId string) ApiDocuments

Documents return an ApiDocuments client.

func (*Client) Health

func (c *Client) Health() ApiHealth

Health return an ApiHealth client.

func (*Client) Indexes

func (c *Client) Indexes() ApiIndexes

Indexes return an ApiIndexes client.

func (*Client) Keys

func (c *Client) Keys() ApiKeys

Keys return an ApiKeys client.

func (*Client) Search

func (c *Client) Search(indexId string) ApiSearch

Search return an ApiSearch client.

func (*Client) Stats

func (c *Client) Stats() ApiStats

Stats return an ApiStats client.

func (*Client) StopWords

func (c *Client) StopWords(indexId string) ApiStopWords

StopWords return an ApiStopWords client.

func (*Client) Updates

func (c *Client) Updates(indexId string) ApiUpdates

Updates return an ApiUpdates client.

func (*Client) Version

func (c *Client) Version() ApiVersion

Version return an ApiVersion client.

type Config

type Config struct {

	// Host is the host of your meilisearch database
	// Example: 'http://localhost:7700'
	Host string

	// APIKey is optional
	APIKey string
}

Config configure the Client

type CreateApiKeyRequest

type CreateApiKeyRequest struct {
	Description string   `json:"description"`
	Acl         []ACL    `json:"acl"`
	Indexes     []string `json:"indexes"`
	ExpireAt    int64    `json:"expiresAt"`
}

type CreateIndexRequest

type CreateIndexRequest struct {
	Name   string `json:"name"`
	UID    string `json:"uid,omitempty"`
	Schema Schema `json:"schema,omitempty"`
}

type CreateIndexResponse

type CreateIndexResponse struct {
	Name      string    `json:"name"`
	UID       string    `json:"uid"`
	Schema    Schema    `json:"schema,omitempty"`
	UpdateID  int64     `json:"updateId,omitempty"`
	CreatedAt time.Time `json:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt"`
}

type ErrCode

type ErrCode int
const (
	ErrCodeUnknown        ErrCode = 0
	ErrCodeMarshalRequest ErrCode = iota + 1
	ErrCodeRequestCreation
	ErrCodeRequestExecution
	ErrCodeResponseStatusCode
	ErrCodeResponseReadBody
	ErrCodeResponseUnmarshalBody
	ErrCodeUrlParsing
)

type Error

type Error struct {
	// Endpoint is the path of the request (host is not in)
	Endpoint string

	// Method is the HTTP verb of the request
	Method string

	// Function name used
	Function string

	// APIName is which part/module of the api
	APIName string

	// RequestToString is the raw request into string ('empty request' if not present)
	RequestToString string

	// RequestToString is the raw request into string ('empty response' if not present)
	ResponseToString string

	// MeilisearchMessage is the raw request into string ('empty meilisearch message' if not present)
	MeilisearchMessage string

	// StatusCode of the request
	StatusCode int

	// StatusCode expected by the endpoint to be considered as a success
	StatusCodeExpected []int

	// OriginError is the origin error that produce the current Error. It can be nil in case of a bad status code.
	OriginError error

	// ErrCode is the internal error code that represent the different step when executing a request that can produce
	// an error.
	ErrCode ErrCode
	// contains filtered or unexported fields
}

Error is the internal error structure that all exposed method use. So ALL errors returned by this library can be cast to this struct (as a pointer)

func (Error) Error

func (e Error) Error() string

Error return a well human formatted message.

func (*Error) ErrorBody

func (e *Error) ErrorBody(body []byte)

func (*Error) WithErrCode

func (e *Error) WithErrCode(err ErrCode, errs ...error) *Error

func (*Error) WithMessage

func (e *Error) WithMessage(str string, errs ...error) *Error

type Index

type Index struct {
	Name      string    `json:"name"`
	UID       string    `json:"uid"`
	CreatedAt time.Time `json:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt"`
}

type ListDocumentsRequest

type ListDocumentsRequest struct {
	Offset               int64    `json:"offset,omitempty"`
	Limit                int64    `json:"limit,omitempty"`
	AttributesToRetrieve []string `json:"attributesToRetrieve,omitempty"`
}

type ListSynonymsResponse

type ListSynonymsResponse map[string][]string

type RawAttribute

type RawAttribute struct {
	Displayed bool `json:"displayed"`
	Indexed   bool `json:"indexed"`
	Ranked    bool `json:"ranked"`
}

type RawSchema

type RawSchema struct {
	Identifier string                  `json:"identifier"`
	Attributes map[string]RawAttribute `json:"attributes"`
}

type Schema

type Schema map[string][]SchemaAttributes

type SchemaAttributes

type SchemaAttributes string
const (
	SchemaAttributesDisplayed  SchemaAttributes = "displayed"
	SchemaAttributesIndexed    SchemaAttributes = "indexed"
	SchemaAttributesRanked     SchemaAttributes = "ranked"
	SchemaAttributesIdentifier SchemaAttributes = "identifier"
)

type SearchRequest

type SearchRequest struct {
	Query                 string
	Filters               string
	Offset                int64
	Limit                 int64
	TimeoutMs             int64
	CropLength            int64
	AttributesToRetrieve  []string
	AttributesToSearchIn  []string
	AttributesToCrop      []string
	AttributesToHighlight []string
	Matches               bool
}

type SearchResponse

type SearchResponse struct {
	Hits             []interface{} `json:"hits"`
	Offset           int64         `json:"offset"`
	Limit            int64         `json:"limit"`
	ProcessingTimeMs int64         `json:"processingTimeMs"`
	Query            string        `json:"query"`
}

type Settings

type Settings struct {
	RankingOrder  []string          `json:"rankingOrder,omitempty"`
	DistinctField string            `json:"distinctField,omitempty"`
	RankingRules  map[string]string `json:"rankingRules,omitempty"`
}

type Stats

type Stats struct {
	NumberOfDocuments int64            `json:"numberOfDocuments"`
	IsIndexing        bool             `json:"isIndexing"`
	FieldsFrequency   map[string]int64 `json:"fieldsFrequency"`
}

type Synonym

type Synonym struct {
	Input    string   `json:"input,omitempty"`
	Synonyms []string `json:"synonyms"`
}

type SystemInformation

type SystemInformation struct {
	MemoryUsage    float64   `json:"memoryUsage"`
	ProcessorUsage []float64 `json:"processorUsage"`
	Global         struct {
		TotalMemory int64 `json:"totalMemory"`
		UsedMemory  int64 `json:"usedMemory"`
		UsedSwap    int64 `json:"usedSwap"`
		InputData   int64 `json:"inputData"`
		OutputData  int64 `json:"outputData"`
	} `json:"global"`
	Process struct {
		Memory int64 `json:"memory"`
		CPU    int64 `json:"cpu"`
	} `json:"process"`
}

type SystemInformationPretty

type SystemInformationPretty struct {
	MemoryUsage    string   `json:"memoryUsage"`
	ProcessorUsage []string `json:"processorUsage"`
	Global         struct {
		TotalMemory string `json:"totalMemory"`
		UsedMemory  string `json:"usedMemory"`
		UsedSwap    string `json:"usedSwap"`
		InputData   string `json:"inputData"`
		OutputData  string `json:"outputData"`
	} `json:"global"`
	Process struct {
		Memory string `json:"memory"`
		CPU    string `json:"cpu"`
	} `json:"process"`
}

type Unknown

type Unknown map[string]interface{}

type Update

type Update struct {
	Status      UpdateStatus `json:"status"`
	UpdateID    int64        `json:"updateId"`
	Type        Unknown      `json:"type"`
	Error       string       `json:"error"`
	EnqueuedAt  time.Time    `json:"enqueuedAt"`
	ProcessedAt time.Time    `json:"processedAt"`
}

type UpdateApiKeyRequest

type UpdateApiKeyRequest struct {
	Description string   `json:"description"`
	Acl         []ACL    `json:"acl"`
	Indexes     []string `json:"indexes"`
	Revoked     bool     `json:"revoked"`
}

type UpdateStatus

type UpdateStatus string
const (
	UpdateStatusUnknown   UpdateStatus = "unknown"
	UpdateStatusEnqueued  UpdateStatus = "enqueued"
	UpdateStatusProcessed UpdateStatus = "processed"
	UpdateStatusFailed    UpdateStatus = "failed"
)

func AwaitAsyncUpdateId

func AwaitAsyncUpdateId(api ApiWithIndexID, updateId *AsyncUpdateId) UpdateStatus

AwaitAsyncUpdateId check each 25ms the status of a AsyncUpdateId. This method should be avoided.

type Version

type Version struct {
	CommitSha  string    `json:"commitSha"`
	BuildDate  time.Time `json:"buildDate"`
	PkgVersion string    `json:"pkgVersion"`
}

Jump to

Keyboard shortcuts

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