solr package - github.com/mecenat/solr - Go Packages

solr

package module
v1.7.1 Latest Latest
Warning

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

Go to latest
Published: Mar 25, 2026 License: MIT Imports: 13 Imported by: 1

README

solr

A Solr client written in Go

Designed for Solr 8.5 (Should support earlier versions as well)

Provides clients for Solr's Request API, Schema API & Core Admin API

Currently supports only JSON and basic CRUDL actions.

Installation

go get -u github.com/mecenat/solr

Usage

To create a new solr Client you need first to create a Connection. To create a Connection you need the host location (e.g. http://localhost:8983), the core name, and a http client. Use solr.NewDefaultHTTPClient() for a client with sensible connection pooling defaults. Sending your own client could be useful when you need to wrap the client with another service, for example if you want to use AWS's X-Ray service to trace your API's calls or granular control over connection limits.

When using a single server:

package main

import "github.com/mecenat/solr"

func main() {
	conn, err := solr.NewConnection("host", "core", solr.NewDefaultHTTPClient())
	if err != nil {
				...
	}
	slr, err := solr.NewSingleClient(conn)
	if err != nil {
	      ...
	}

When using a the Primary-Replica paradigm:

package main

import "github.com/mecenat/solr"

func main() {
	primaryConn, err := solr.NewConnection("primaryHost", "core", solr.NewDefaultHTTPClient())
	if err != nil {
				...
	}
	replicaConn, err := solr.NewConnection("replicaHost", "core", solr.NewDefaultHTTPClient())
	if err != nil {
				...
	}
	slr, err := solr.NewPrimaryReplicaClient(primaryConn, replicaConn)
	if err != nil {
	      ...
	}

Aside from the normal Connection you can you a RetryableConnection which implements Hashicorp's retryable HttpClient specifying the max timeout and provide that connection to the clients.

package main

import "github.com/mecenat/solr"

func main() {
	retConn, err := solr.NewRetryableConnection("host", "core", solr.NewDefaultHTTPClient(), 500*time.Millisecond)
	if err != nil {
				...
	}
	slr, err := solr.NewSingleClient(retConn)
	if err != nil {
	      ...
	}

To access Solr's Core Admin API you need to create a separate client as follows:

package main

import "github.com/mecenat/solr"

func main() {
	ctx := context.Background()
	ca, err := solr.NewCoreAdmin(ctx, "host", solr.NewDefaultHTTPClient())
	if err != nil {
				...
	}

To access Solr's Schema API you also need a separate client as follows:

package main

import "github.com/mecenat/solr"

func main() {
	ctx := context.Background()
	sa, err := solr.NewSchemaAPI(ctx, "host", "core", solr.NewDefaultHTTPClient())
	if err != nil {
				...
	}

Releasing

To create a new release, push a semver tag to master:

git tag v1.5.0
git push origin v1.5.0

This triggers a GitHub Actions workflow that runs tests and creates a GitHub release with auto-generated notes.

License

This library is licensed under the MIT license. It depends on github.com/hashicorp/go-cleanhttp and github.com/hashicorp/go-retryablehttp, which is licensed under the Mozilla Public License (MPL).

Documentation

Overview

Package solr provides a solr client that enables the user to easily connect to one or more solr servers with support for the the basic CRUDL functionality

Index

Constants

View Source
const (
	CoreAdminOptionIndexInfo         = "indexInfo"
	CoreAdminOptionName              = "name"
	CoreAdminOptionInstanceDir       = "instanceDir"
	CoreAdminOptionConfig            = "config"
	CoreAdminOptionSchema            = "schema"
	CoreAdminOptionDataDir           = "dataDir"
	CoreAdminOptionConfigSet         = "configSet"
	CoreAdminOptionCollection        = "collection"
	CoreAdminOptionShard             = "shard"
	CoreAdminOptionAsync             = "async"
	CoreAdminOptionCore              = "core"
	CoreAdminOptionOther             = "other"
	CoreAdminOptionAction            = "action"
	CoreAdminOptionDeleteIndex       = "deleteIndex"
	CoreAdminOptionDeleteDataDir     = "deleteDataDir"
	CoreAdminOptionDeleteInstanceDir = "deleteInstanceDir"
	CoreAdminOptionIndexDir          = "indexDir"
	CoreAdminOptionSourceCore        = "srcCore"
	CoreAdminOptionPath              = "path"
	CoreAdminOptionTargetCore        = "targetCore"
	CoreAdminOptionRanges            = "ranges"
	CoreAdminOptionSplitKey          = "split.key"
	CoreAdminOptionRequestID         = "requestid"
	CoreAdminActionStatus            = "STATUS"
	CoreAdminActionCreate            = "CREATE"
	CoreAdminActionReload            = "RELOAD"
	CoreAdminActionRename            = "RENAME"
	CoreAdminActionSwap              = "SWAP"
	CoreAdminActionUnload            = "UNLOAD"
	CoreAdminActionMergeIndexes      = "MERGEINDEXES"
	CoreAdminActionSplit             = "SPLIT"
	CoreAdminActionRequestStatus     = "REQUESTSTATUS"
	CoreAdminActionRecover           = "REQUESTRECOVERY"
)

CoreAdmin Option & Action constants

View Source
const (
	OptionDebug                        = "debug"
	OptionDefType                      = "defType"
	OptionQ                            = "q"
	OptionQOperation                   = "q.op"
	OptionFilter                       = "fq"
	OptionFieldList                    = "fl"
	OptionRows                         = "rows"
	OptionStart                        = "start"
	OptionSort                         = "sort"
	OptionWT                           = "wt"
	OptionCommit                       = "commit"
	OptionOverwrite                    = "overwrite"
	OptionCommitWithin                 = "commitWithin"
	OptionWaitSearcher                 = "waitSearcher"
	OptionMaxSegments                  = "maxSegments"
	OptionExpungeDeletes               = "expungeDeletes"
	OptionMM                           = "mm"
	OptionBoost                        = "boost"
	OptionQueryFields                  = "qf"
	OptionBoostQuery                   = "bq"
	OptionBoostFunctions               = "bf"
	OptionUserFields                   = "uf"
	OptionCollapseField                = "field"
	OptionCollapseMax                  = "max"
	OptionCollapseMin                  = "min"
	OptionCollapseSort                 = "sort"
	OptionCollapseNullPolicy           = "nullPolicy"
	OptionCollapseHint                 = "hint"
	OptionCollapseSize                 = "size"
	OptionExpand                       = "expand"
	OptionExpandSort                   = "expand.sort"
	OptionExpandQ                      = "expand.q"
	OptionExpandFQ                     = "expand.fq"
	OptionExpandRows                   = "expand.rows"
	OptionFacet                        = "facet"
	OptionFacetField                   = "facet.field"
	OptionLimit                        = "limit"
	OptionPrefix                       = "prefix"
	OptionContains                     = "contains"
	OptionMissing                      = "missing"
	OptionMinCount                     = "mincount"
	OptionExcludeTerms                 = "excludeTerms"
	OptionFacetPivot                   = "facet.pivot"
	OptionGroup                        = "group"
	OptionGroupField                   = "group.field"
	OptionGroupNGroups                 = "group.ngroups"
	OptionGroupLimit                   = "group.limit"
	OptionGroupOffset                  = "group.offset"
	OptionGroupQuery                   = "group.query"
	OptionGroupFunc                    = "group.func"
	OptionGroupSort                    = "group.sort"
	ReturnTypeJSON                     = "json"
	QOperationOR                       = "OR"
	QOperationAND                      = "AND"
	DefTypeDisMax            DefType   = "dismax"
	DefTypeEDisMax           DefType   = "edismax"
	DefTypeStandard          DefType   = "lucene"
	DebugTypeQuery           DebugType = "query"
	DebugTypeTiming          DebugType = "timing"
	DebugTypeResults         DebugType = "results"
	DebugTypeAll             DebugType = "all"
)

Query Options and other constants

View Source
const (
	NullPolicyIgnore   NullPolicy = "ignore"
	NullPolicyExpand   NullPolicy = "expand"
	NullPolicyCollapse NullPolicy = "collapse"
	HintTopFC          Hint       = "top_fc"
)

Constants to secure proper NullPolicy & Hint usage

View Source
const (
	ActionSet                 = "set"
	ActionAdd                 = "add"
	ActionAddDistinct         = "add-distinct"
	ActionRemove              = "remove"
	ActionRemoveRegex         = "removeregex"
	ActionIncrement           = "inc"
	CommandAdd        Command = "add"
	CommandDelete     Command = "delete"
	CommandCommit     Command = "commit"
	CommandRollback   Command = "rollback"
	CommandOptimize   Command = "optimize"
)

Constants for different actions and commands used for the `/update` endpoint

Variables

View Source
var (
	ErrMoreParamsPath  = errors.New("only one of path, targetCore may be defined")
	ErrMoreParamsRange = errors.New("only one of range, split.key may be defined")
)

Errors that can be returned

View Source
var (
	ErrInvalidDefType   = errors.New("invalid defType, please use one of the provided ones")
	ErrInvalidDebugType = errors.New("invalid debugType, please use one of the provided ones")
)

Returned validation errors

View Source
var (
	ErrParamsRequired    = errors.New("param field is required for the CollapsingQParser")
	ErrTooManyParams     = errors.New("only one of Max, Min or Sort may be populated")
	ErrInvalidNullPolicy = errors.New("invalid null policy, please use one of the provided")
	ErrInvalidHint       = errors.New("invalid hint, please use one of the provided")
)

Possible errors returned from improper use of the Collapsing Query Parser

View Source
var (
	ErrFieldNotFound        = errors.New("field not found")
	ErrFieldTypeNotFound    = errors.New("field type not found")
	ErrDynamicFieldNotFound = errors.New("dynamic field not found")
	ErrCopyFieldNotFound    = errors.New("copy field not found")
)

Various errors returned from the schema API

View Source
var ErrInvalidConfig = errors.New("invalid configuration: no host or core provided")

ErrInvalidConfig is returned when the hostname or corename are empty

Functions

func BoostField

func BoostField(field string, boost float64) string

BoostField is a helper function to properly format field boosting

func NewDefaultHTTPClient added in v1.6.0

func NewDefaultHTTPClient() *http.Client

NewDefaultHTTPClient returns an *http.Client configured with sensible defaults for connection pooling and keep-alive. Use this instead of http.DefaultClient which only keeps 2 idle connections per host, causing excessive reconnections under concurrent load.

Types

type Analyzer

type Analyzer struct {
	Tokenizer map[string]interface{}   `json:"tokenizer"`
	Filters   []map[string]interface{} `json:"filters"`
}

Analyzer represents the analyzer entity. An analyzer examines the text of fields and generates a token stream. For more info: https://lucene.apache.org/solr/guide/8_5/analyzers.html

type Client

type Client interface {
	// SetBasicAuth sets the authentication credentials if needed.
	SetBasicAuth(username, password string)

	// Ping checks the connectivity of the solr server. It usually just returns with
	// Status = OK and a default response header, therefore this function just
	// returns an error in case there is no response, or an unexpected one.
	Ping(ctx context.Context) error

	// Search performs a query to the solr server by using the `/select` endpoint, with the provided query
	// parameters. The query input can be easily created utilizing the provided helpers (check examples).
	// Currently only simple searches are supported.
	// For more info:
	// https://lucene.apache.org/solr/guide/8_5/overview-of-searching-in-solr.html
	Search(ctx context.Context, q *Query) (*Response, error)

	// Get performs a realtime get call to the solr server that returns the latest version of the document specified
	// by its id (uniqueKey field) without the associated cost of reopening a searcher. This is primarily useful
	// when using Solr as a NoSQL data store and not just a search index. The provided filter should
	// follow the format of the `fq` parameter but be concatenated in one string. For more info:
	// https://lucene.apache.org/solr/guide/8_5/realtime-get.html
	Get(ctx context.Context, id, filter string) (*Response, error)

	// BatchGet performs a realtime get call to the solr server that returns the latest version of multiple documents
	// specified by their id (uniqueKey field) and filtered by the provided filter. The provided filter should
	// follow the format of the `fq` parameter but be concatenated in one string. For more info:
	// https://lucene.apache.org/solr/guide/8_5/realtime-get.html
	BatchGet(ctx context.Context, ids []string, filter string) (*Response, error)

	// Create adds a single document via JSON to the solr service. It calls the `/update/json/docs` endpoint.
	// Therefore the provided interface (item) must be a valid JSON object. This method accepts extra
	// options that are passed to the service as part of the request query. For more info:
	// https://lucene.apache.org/solr/guide/8_5/uploading-data-with-index-handlers.html#adding-a-single-json-document
	Create(ctx context.Context, item interface{}, opts *WriteOptions) (*Response, error)

	// BatchCreate adds multiple documents at once via JSON to the solr service. It calls the `/update` endpoint.
	// Therefore the provided interface (items) must be a valid array of JSON objects. This method accepts
	// extra options that are passed to the service as part of the request query. For more info:
	// https://lucene.apache.org/solr/guide/8_5/uploading-data-with-index-handlers.html#adding-multiple-json-documents
	BatchCreate(ctx context.Context, items interface{}, opts *WriteOptions) (*Response, error)

	// Update allows for partial updates of documents utilizing the "atomic" and the "in-place" updates approach.
	// The expected Fields input can be easily created using the provided helpers (check examples). This method
	// accepts extra options that are passed to the service as part of the request query. For more info:
	// https://lucene.apache.org/solr/guide/8_5/updating-parts-of-documents.html#atomic-updates
	Update(ctx context.Context, item *UpdatedFields, opts *WriteOptions) (*Response, error)

	// DeleteByID sends a JSON update command that deletes the document specified by its id (uniqueKey field).
	// It calls the `/update` endpoint and sends Solr JSON. This method accepts extra options that are
	// passed to the service as part of the request query. For more info:
	// https://lucene.apache.org/solr/guide/8_5/uploading-data-with-index-handlers.html#sending-json-update-commands
	DeleteByID(ctx context.Context, id string, opts *WriteOptions) (*Response, error)

	// DeleteByID sends a JSON update command that deletes the documents matching the given query. The query format
	// should follow the syntax of the Q parameter for the Search endpoint. It calls the `/update` endpoint and
	// sends Solr JSON. This method accepts extra options that are passed to the service as part of the
	// request query. For more info:
	// https://lucene.apache.org/solr/guide/8_5/uploading-data-with-index-handlers.html#sending-json-update-commands
	DeleteByQuery(ctx context.Context, query string, opts *WriteOptions) (*Response, error)

	// Clear is a helper method that removes all documents from the solr server. Use with caution.
	// It sends a DeleteByQuery request where the query is `*:*` and commit=true.
	Clear(ctx context.Context) (*Response, error)

	// Commit sends a JSON update command that commits all uncommited changes. Unless specified from one of the
	// options all write methods of this library will not commit their changes, therefore this method should
	// be called at the end of the a transaction to ensure that the indexes are properly updated.
	// For more info:
	// https://lucene.apache.org/solr/guide/8_5/uploading-data-with-index-handlers.html#sending-json-update-commands
	Commit(ctx context.Context, opts *CommitOptions) (*Response, error)

	// Rollback sends a JSON update command that rollbacks all uncommited changes. Unless specified from one of the
	// options all write methods of this library will not commit their changes, therefore this method should
	// be called if some action of the transaction returns an error and data cleaning is necessary.
	// For more info:
	// https://lucene.apache.org/solr/guide/8_5/uploading-data-with-index-handlers.html#sending-json-update-commands
	Rollback(ctx context.Context) (*Response, error)

	// Optimize sends a JSON update command that requests Solr to merge internal data structures. For a large index,
	// optimization will take some time to complete, but by merging many small segment files into larger segments, \
	// search performance may improve. More info:
	// https://lucene.apache.org/solr/guide/8_5/uploading-data-with-index-handlers.html#commit-and-optimize-during-updates
	Optimize(ctx context.Context, opts *OptimizeOptions) (*Response, error)

	// CustomUpdate allows the creation of a request to the `/update` endpoint that can include more than one update
	// command or for those that want a more finegrained request.
	CustomUpdate(ctx context.Context, item *UpdateBuilder, opts *WriteOptions) (*Response, error)
}

Client is the interface encompasing all the solr service methods

func NewPrimaryReplicaClient

func NewPrimaryReplicaClient(primaryConn, replicaConn connection) (Client, error)

NewPrimaryReplicaClient returns two connections from the provided host and cores, one for the primary server and another for the replica. By default it is assumed that the primary server is used for writing data, and the replica server for reading data.

func NewSingleClient

func NewSingleClient(conn connection) (Client, error)

NewSingleClient returns a connection to the solr client provided by the given host and core.

type CollapseParams

type CollapseParams struct {
	Field      string
	Min        string
	Max        string
	Sort       string
	NullPolicy *NullPolicy
	Hint       *Hint
	Size       string
}

CollapseParams are the available params that can be set when using the Collapsing Query Parser

type Command

type Command string

Command is used to restrict the available update commands that can be included in the body of a request to the `/update` endpoint.

func (Command) String

func (c Command) String() string

type CommitOptions

type CommitOptions struct {
	DoNotWaitSearcher bool
	ExpungeDeletes    bool
}

CommitOptions are the available options to a commit update command.

type Connection

type Connection struct {
	Host     string
	Core     string
	Username string
	Password string
	// contains filtered or unexported fields
}

Connection represents the connection to the solr server and includes information about the address of the server and and the client to be used for connecting to it.

func NewConnection added in v1.3.0

func NewConnection(host, core string, client *http.Client) (*Connection, error)

NewConnection ...

type CopyField

type CopyField struct {
	Source   string `json:"source"`
	Dest     string `json:"dest"`
	MaxChars int    `json:"maxChars,omitempty"`
}

CopyField represents a solr copy field rule, solr's mechanism for making copies of fields so that you can apply several distinct field types to a single piece of incoming information. The name of the field you want to copy is the source, and the name of the copy is the destination. For more info: https://lucene.apache.org/solr/guide/8_5/copying-fields.html

type CoreAdmin

type CoreAdmin struct {
	Path string
	// contains filtered or unexported fields
}

CoreAdmin contains a connectin to solr.

func NewCoreAdmin

func NewCoreAdmin(ctx context.Context, host string, client *http.Client) (*CoreAdmin, error)

NewCoreAdmin returns a new core admin, creating a connection to solr using the provided http client and host, core info.

func (*CoreAdmin) Create

func (a *CoreAdmin) Create(ctx context.Context, name string, opts *CoreCreateOpts) (*CoreAdminResponse, error)

Create creates a new core and registers it. For more info: https://lucene.apache.org/solr/guide/8_5/coreadmin-api.html#coreadmin-create

func (*CoreAdmin) Merge

func (a *CoreAdmin) Merge(ctx context.Context, core string, opts *CoreMergeOpts) (*CoreAdminResponse, error)

Merge merges one or more indexes to another index. The target core index must already exist and have a compatible schema with the one or more indexes that will be merged to it. Another commit on the target core should also be performed after the merge is complete. For more info: https://lucene.apache.org/solr/guide/8_5/coreadmin-api.html#coreadmin-mergeindexes

func (*CoreAdmin) Recover

func (a *CoreAdmin) Recover(ctx context.Context, core string) (*CoreAdminResponse, error)

Recover manually asks a core to recover by synching with the leader. This should be considered an "expert" level command and should be used in situations where the node (SorlCloud replica) is unable to become active automatically. For more info https://lucene.apache.org/solr/guide/8_5/coreadmin-api.html#coreadmin-requestrecovery

func (*CoreAdmin) Reload

func (a *CoreAdmin) Reload(ctx context.Context, core string) (*CoreAdminResponse, error)

Reload loads a new core from the configuration of an existing, registered Solr core. While the new core is initializing, the existing one will continue to handle requests. When the new Solr core is ready, it takes over and the old core is unloaded. For More info: https://lucene.apache.org/solr/guide/8_5/coreadmin-api.html#coreadmin-reload

func (*CoreAdmin) Rename

func (a *CoreAdmin) Rename(ctx context.Context, core, other, asyncID string) (*CoreAdminResponse, error)

Rename changes the name of a Solr core. An asyncID may be provided in order to track this action which will be processed asynchronously. For more info: https://lucene.apache.org/solr/guide/8_5/coreadmin-api.html#coreadmin-rename

func (*CoreAdmin) RequestStatus

func (a *CoreAdmin) RequestStatus(ctx context.Context, id string) (*CoreAdminResponse, error)

RequestStatus returns the status of an already submitted asynchronous CoreAdmin API call. For more info: https://lucene.apache.org/solr/guide/8_5/coreadmin-api.html#coreadmin-requeststatus

func (*CoreAdmin) SetBasicAuth

func (a *CoreAdmin) SetBasicAuth(username, password string)

SetBasicAuth sets the authentication credentials if needed.

func (*CoreAdmin) Split

func (a *CoreAdmin) Split(ctx context.Context, core string, opts *CoreSplitOpts) (*CoreAdminResponse, error)

Split splits an index into two or more indexes. The index being split can continue to handle requests. The split pieces can be placed into a specified directory on the server’s filesystem or it can be merged into running Solr cores. For more info: https://lucene.apache.org/solr/guide/8_5/coreadmin-api.html#coreadmin-split

func (*CoreAdmin) Status

func (a *CoreAdmin) Status(ctx context.Context, core string, noIndexInfo bool) (*CoreAdminResponse, error)

Status returns the status of all running Solr cores, or status for only the named core. If the noIndexInfo option is true information about the index will not be returned with a core. For more info: https://lucene.apache.org/solr/guide/8_5/coreadmin-api.html#coreadmin-status

func (*CoreAdmin) Swap

func (a *CoreAdmin) Swap(ctx context.Context, core, other, asyncID string) (*CoreAdminResponse, error)

Swap atomically swaps the names used to access two existing Solr cores. This can be used to swap new content into production. For more info: https://lucene.apache.org/solr/guide/8_5/coreadmin-api.html#coreadmin-swap

func (*CoreAdmin) Unload

func (a *CoreAdmin) Unload(ctx context.Context, core string, opts *CoreUnloadOpts) (*CoreAdminResponse, error)

Unload removes a core from Solr. Requires the name of the core to be unloaded. For more info: https://lucene.apache.org/solr/guide/8_5/coreadmin-api.html#coreadmin-unload

type CoreAdminResponse

type CoreAdminResponse struct {
	Header       *ResponseHeader                `json:"responseHeader"`
	Error        *ResponseError                 `json:"error"`
	Status       map[string]*CoreStatusResponse `json:"status"`
	ReqStatus    string                         `json:"STATUS"`
	Response     interface{}                    `json:"response"`
	InitFailures interface{}                    `json:"initFailures"`
	Core         string                         `json:"core"`
}

CoreAdminResponse represents the response from the solr core admin API. It usually contains Header information, the response data or an error in case of erroneous response. Also it can contain the core's or a request's status, failures that might have happened during the initiation procedure as well as core information.

type CoreCreateOpts

type CoreCreateOpts struct {
	InstanceDir string
	Config      string
	Schema      string
	DataDir     string
	ConfigSet   string
	Collection  string
	Shard       string
	AsyncID     string
}

CoreCreateOpts are the optional properties that can be provided when creating a new core.

type CoreMergeOpts

type CoreMergeOpts struct {
	IndexDir []string
	SrcCore  []string
	AsyncID  string
}

CoreMergeOpts are the optional properties that can be provided when merging a core.

type CoreSplitOpts

type CoreSplitOpts struct {
	Path       []string
	TargetCore []string
	Ranges     string
	SplitKey   string
	AsyncID    string
}

CoreSplitOpts are the optional properties that can be provided when splitting a core. Path & TargetCore may not have a value simultaneously, the same goes for Ranges & SplitKey.

type CoreStatusResponse

type CoreStatusResponse struct {
	Name        string        `json:"name"`
	InstanceDir string        `json:"instanceDir"`
	DataDir     string        `json:"dataDir"`
	Config      string        `json:"config"`
	Schema      string        `json:"schema"`
	StartTime   time.Time     `json:"startTime"`
	Uptime      time.Duration `json:"uptime"`
	Index       *IndexData    `json:"index"`
}

CoreStatusResponse contains information about a core and its status.

type CoreUnloadOpts

type CoreUnloadOpts struct {
	DeleteIndex       bool
	DeleteDataDir     bool
	DeleteInstanceDir bool
	AsyncID           string
}

CoreUnloadOpts are the optional properties that can be provided when unloading a core.

type DebugType

type DebugType string

DebugType is used to restrict the available debug types for a `/search` request

func (DebugType) String

func (dt DebugType) String() string

type DefType

type DefType string

DefType is used to restrict the available defTypes for a `/search` request

func (DefType) String

func (dt DefType) String() string

type Doc

type Doc map[string]interface{}

Doc is essentialy a map[string]interface{}

func (*Doc) ToBytes

func (d *Doc) ToBytes() ([]byte, error)

ToBytes returs a byte slice to simplify unmarshaling to JSON

type Docs

type Docs []*Doc

Docs represents an array of doc

func (Docs) ToBytes

func (d Docs) ToBytes() ([]byte, error)

ToBytes returs a byte slice to simplify unmarshaling to JSON

type DynamicField

type DynamicField Field

DynamicField is just like a regular field except it has a name with a wildcard in it. For more info: https://lucene.apache.org/solr/guide/8_5/dynamic-fields.html

type ErrorDetail added in v1.1.0

type ErrorDetail interface {
	String() string
	Item() map[string]interface{}
}

ErrorDetail is an interface to interpret the details of an error. Solr tends to be inconsistent about the type of the detail, therefore an interface is needed to cover all possible scenarios.

type ErrorDetailObj added in v1.1.0

type ErrorDetailObj struct {
	Messages    []string               `json:"errorMessages"`
	Command     string                 `json:"command"`
	CommandItem map[string]interface{} `json:"item"`
}

ErrorDetailObj provides detailed information on the errors that might arise when multiple commands are sent in a batch.

func (*ErrorDetailObj) Item added in v1.1.0

func (d *ErrorDetailObj) Item() map[string]interface{}

Item returns the item causing the error

func (*ErrorDetailObj) String added in v1.1.0

func (d *ErrorDetailObj) String() string

type ErrorDetailString added in v1.1.0

type ErrorDetailString string

ErrorDetailString provides information about the details of the error.

func (*ErrorDetailString) Item added in v1.1.0

func (d *ErrorDetailString) Item() map[string]interface{}

Item returns an empty map here.

func (*ErrorDetailString) String added in v1.1.0

func (d *ErrorDetailString) String() string

type ExpandOptions

type ExpandOptions struct {
	Sort string
	Rows int
	Q    string
	FQ   string
}

ExpandOptions are the available options to set for the expand component

type Facet

type Facet struct {
	Field        string
	Prefix       string
	Contains     string
	Limit        int
	MinCount     int
	Missing      bool
	ExcludeTerms []string
}

Facet represent a facet for a specific field along with some of the available options for that facet.

type FacetCounts

type FacetCounts struct {
	Queries   map[string]int         `json:"facet_queries"`
	Fields    *FacetFields           `json:"facet_fields"`
	Dates     map[string]interface{} `json:"facet_dates"`
	Ranges    map[string]*Range      `json:"facet_ranges"`
	Intervals map[string]interface{} `json:"facet_intervals"`
	Heatmaps  map[string]interface{} `json:"facet_heatmaps"`
	Pivot     map[string][]*Pivot    `json:"facet_pivot"`
}

FacetCounts is populated whenever the query to solr includes facets. Each of the following attributes get populated depending on the actual facet query. 'Fields' attribute includes a helper to retrieve the facets in a string: float format.

type FacetFields

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

FacetFields is the facet_field parameter which in Solr contains an array that alternates between string and numbers. In order to make this more Go-friendly it's using a custom unmarshaler and a getter that helps format the results in a map[string]float64.

func (*FacetFields) Get

func (f *FacetFields) Get(s string) map[string]float64

Get returns the facets on the given field in a Go-friendly way.

func (*FacetFields) UnmarshalJSON

func (f *FacetFields) UnmarshalJSON(b []byte) error

UnmarshalJSON implements the unmarshaler interface.

type Field

type Field struct {
	Name    string      `json:"name"`
	Type    string      `json:"type"`
	Default interface{} `json:"default,omitempty"`
	FieldDefaultProperties
}

Field represents a solr field. For more info: https://lucene.apache.org/solr/guide/8_5/defining-fields.html#field-properties

type FieldDefaultProperties

type FieldDefaultProperties struct {
	Indexed                  *bool `json:"indexed,omitempty"`
	Stored                   *bool `json:"stored,omitempty"`
	DocValues                *bool `json:"docValues,omitempty"`
	SortMissingFirst         *bool `json:"sortMissingFirst,omitempty"`
	SortMissingLast          *bool `json:"sortMissingLast,omitempty"`
	MultiValued              *bool `json:"multiValued,omitempty"`
	Uninvertible             *bool `json:"uninvertible,omitempty"`
	OmitNorms                *bool `json:"omitNorms,omitempty"`
	OmitTermFreqAndPositions *bool `json:"omitTermFreqAndPositions,omitempty"`
	OmitPositions            *bool `json:"omitPositions,omitempty"`
	TermVectors              *bool `json:"termVectors,omitempty"`
	TermPositions            *bool `json:"termPositions,omitempty"`
	TermOffsets              *bool `json:"termOffsets,omitempty"`
	TermPayloads             *bool `json:"termPayloads,omitempty"`
	Required                 *bool `json:"required,omitempty"`
	UseDocValuesAsStored     *bool `json:"useDocValuesAsStored,omitempty"`
	Large                    *bool `json:"large,omitempty"`
}

FieldDefaultProperties represents the defualt properties shared by field types and fields. These are propertries that can be specified either on the field types, or on individual fields to override the values provided by the field types. Built according to schema version 1.6. For more info: https://lucene.apache.org/solr/guide/8_5/field-type-definitions-and-properties.html#field-default-properties

type FieldType

type FieldType struct {
	Name                      string    `json:"name"`
	CLass                     string    `json:"class"`
	PositionIncrementGap      string    `json:"positionIncrementGap,omitempty"`
	AutoGeneratePhraseQueries string    `json:"autoGeneratePhraseQueries,omitempty"`
	SynonymQueryStyle         string    `json:"synonymQueryStyle,omitempty"`
	EnableGraphQueries        bool      `json:"enableGraphQueries,omitempty"`
	DocValuesFormat           string    `json:"docValuesFormat,omitempty"`
	PostingsFormat            string    `json:"postingsFormat,omitempty"`
	Analyzer                  *Analyzer `json:"analyzer,omitempty"`
	IndexAnalyzer             *Analyzer `json:"indexAnalyzer,omitempty"`
	QueryAnalyzer             *Analyzer `json:"queryAnalyzer,omitempty"`
	FieldDefaultProperties
}

FieldType represents a solr field type. A field type defines the analysis that will occur on a field when documents are indexed or queries are sent to the index. Only a name and the class name are mandatory. For more info: https://lucene.apache.org/solr/guide/8_5/field-type-definitions-and-properties.html#general-properties

type Group

type Group struct {
	Value   interface{}   `json:"groupValue"`
	Matches int           `json:"matches"`
	DocList *ResponseData `json:"doclist"`
}

Group contains a value and the list of documents that belong to the specific group.

type GroupField

type GroupField struct {
	Matches        int      `json:"matches"`
	NumberOfGroups int      `json:"ngroups"`
	Groups         []*Group `json:"groups"`
}

GroupField is populated whenever the query to solr includes grouping. The response contains the total matches (of docs), the number of groups (if requested) and the groups.

type GroupParams

type GroupParams struct {
	Field            string
	Func             []string
	Query            []string
	Limit            int
	Offset           int
	Sort             string
	ShowGroupsNumber bool
}

GroupParams contains the available parameters to finetune result grouping. Of all the params only Field is required

type Grouped

type Grouped struct {
	ByFieldOrFunc map[string]*GroupField
	ByQuery       map[string]*Group
}

Grouped contains the groups that are returned when result grouping is on. Solr is sending a different type of response under the same attribute depending on whether the groups where created by a field or query 0r func. Therefore the Grouped stuct separates them to facilitate unmarshaling and ease of use.

func (*Grouped) UnmarshalJSON

func (g *Grouped) UnmarshalJSON(b []byte) error

UnmarshalJSON implements the unmarshaler interface.

type Hint

type Hint string

Hint represents the Collapse hint param

func (Hint) String

func (h Hint) String() string

type IndexData

type IndexData struct {
	NumDocs                 int64     `json:"numDocs"`
	MaxDoc                  int64     `json:"maxDoc"`
	DeletedDocs             int64     `json:"deletedDocs"`
	IndexHeapUsageBytes     int64     `json:"indexHeapUsageBytes"`
	Version                 int64     `json:"version"`
	SegmentCount            int64     `json:"segmentCount"`
	Current                 bool      `json:"current"`
	HasDeletions            bool      `json:"hasDeletions"`
	Directory               string    `json:"directory"`
	SegmentsFile            string    `json:"segmentsFile"`
	SegmentsFileSizeInBytes int64     `json:"segmentsFileSizeInBytes"`
	UserData                *UserData `json:"userData"`
	LastModified            time.Time `json:"lastModified"`
	SizeInBytes             int64     `json:"sizeInBytes"`
	Size                    string    `json:"size"`
}

IndexData contains information about a core's index.

type ManagedAPI added in v1.1.0

type ManagedAPI struct {
	BasePath string
	// contains filtered or unexported fields
}

ManagedAPI contains a connection to solr

func NewManagedAPI added in v1.1.0

func NewManagedAPI(ctx context.Context, host, core string, client *http.Client) (*ManagedAPI, error)

NewManagedAPI returns a new Managed Resources API, creating a connection to solr using the provided http client, host and core info. https://lucene.apache.org/solr/guide/8_5/managed-resources.html#managed-resources-overview

func (*ManagedAPI) DeleteResource added in v1.1.0

func (m *ManagedAPI) DeleteResource(ctx context.Context, path string) (*ManagedResponse, error)

DeleteResource deletes the specified resource. Requires the path to the resource.

func (*ManagedAPI) RestManager added in v1.1.0

func (m *ManagedAPI) RestManager(ctx context.Context) (*ManagedResponse, error)

RestManager returns all available managed resources on the solr core.

func (*ManagedAPI) RetrieveResource added in v1.1.0

func (m *ManagedAPI) RetrieveResource(ctx context.Context, path string) (*ManagedResponse, error)

RetrieveResource returns the specified resource. Requires the path to the resource.

func (*ManagedAPI) SetBasicAuth added in v1.1.0

func (m *ManagedAPI) SetBasicAuth(username, password string)

SetBasicAuth sets the authentication credentials if needed.

func (*ManagedAPI) SetInitArgs added in v1.1.0

func (m *ManagedAPI) SetInitArgs(ctx context.Context, path string, args map[string]interface{}) (*ManagedResponse, error)

SetInitArgs set the initialization arguments for a managed resource. It requires the path to the managed resource and a map of the init arguments to update. Attention must be given to make sure that the arguments provided are valid init arguments, since solr doesn't check the validity during update but only during core reload.

func (*ManagedAPI) SynonymAdd added in v1.1.0

func (m *ManagedAPI) SynonymAdd(ctx context.Context, listName string, synonyms map[string][]string) (*ManagedResponse, error)

SynonymAdd adds a new synonym mapping in the specified list.

func (*ManagedAPI) SynonymAddOptimal added in v1.1.0

func (m *ManagedAPI) SynonymAddOptimal(ctx context.Context, listName string, synonyms []string) (*ManagedResponse, error)

SynonymAddOptimal creates a mapping for each word in the given slice, just as solr should be doing under the hood in AddSymmetric. The conversion from slice to array of maps is here handled by golang.

func (*ManagedAPI) SynonymAddSymmetric added in v1.1.0

func (m *ManagedAPI) SynonymAddSymmetric(ctx context.Context, listName string, synonyms []string) (*ManagedResponse, error)

SynonymAddSymmetric adds a list of symmetric synonyms. These are expanded into a mapping for each term in the list by solr. Despite what is said in the solr docs tho, currently (v.8.6.1) adding a synonym slice this way does not seem to remove the word for the mapping, ending up having a word being a synonym of itself. SynonymAddOptimal is therefore recommended for this purpose.

func (*ManagedAPI) SynonymDelete added in v1.1.0

func (m *ManagedAPI) SynonymDelete(ctx context.Context, listName string, synonym string) (*ManagedResponse, error)

SynonymDelete removes the specified mapping from the specified synonyms list.

func (*ManagedAPI) SynonymGet added in v1.1.0

func (m *ManagedAPI) SynonymGet(ctx context.Context, listName string, synonym string) (*ManagedResponse, error)

SynonymGet returns the synonym mapping for the specified word in the specified list.

func (*ManagedAPI) SynonymList added in v1.1.0

func (m *ManagedAPI) SynonymList(ctx context.Context, listName string) (*ManagedResponse, error)

SynonymList returns a map of all the synonyms in the specified list.

func (*ManagedAPI) SynonymSetIgnoreCase added in v1.1.0

func (m *ManagedAPI) SynonymSetIgnoreCase(ctx context.Context, listName string, value bool) (*ManagedResponse, error)

SynonymSetIgnoreCase set the desired value to the ignoreCase initialization argument for managed synonym resources.

func (*ManagedAPI) UpsertResource added in v1.1.0

func (m *ManagedAPI) UpsertResource(ctx context.Context, path string, data interface{}) (*ManagedResponse, error)

UpsertResource updates the specified resource. Requires the path to the resource and the resource to be created/updated

type ManagedResource added in v1.1.0

type ManagedResource struct {
	ID              string `json:"resourceId"`
	Class           string `json:"class"`
	ObserversNumber string `json:"numObservers"`
}

ManagedResource represents a managed resource in solr.

type ManagedResponse added in v1.1.0

type ManagedResponse struct {
	Header    *ResponseHeader    `json:"responseHeader"`
	Error     *ResponseError     `json:"error"`
	Resources []*ManagedResource `json:"managedResources"`
	Synonyms  *SynonymMappings   `json:"synonymMappings"`
	RawMap    map[string]interface{}
}

ManagedResponse represents the response from solr's managed resources API. Header and Error (if there is any) will always be populated. The rest are helpers on specific cases. Currently supported cases are when requesting for a list of all managed resources, and for a managed synonyms list.

func (*ManagedResponse) UnmarshalJSON added in v1.1.1

func (r *ManagedResponse) UnmarshalJSON(b []byte) error

UnmarshalJSON implements the unmarshaler interface

type MaxScore

type MaxScore struct {
	Valid bool
	Score float64
}

MaxScore is used as a struct due to the fact that solr may return it as a float or as a string indicating "NaN"

func (*MaxScore) UnmarshalJSON

func (m *MaxScore) UnmarshalJSON(b []byte) error

UnmarshalJSON implements the unmarshaler interface

type NullPolicy

type NullPolicy string

NullPolicy determines the policy when the collapsing field value is null on the document

func (NullPolicy) String

func (p NullPolicy) String() string

type OptimizeOptions

type OptimizeOptions struct {
	DoNotWaitSearcher bool
	MaxSegments       int
}

OptimizeOptions are the available options to an optimize update command.

type PRClient

type PRClient struct {
	PrimaryPath string
	ReplicaPath string
	// contains filtered or unexported fields
}

PRClient implements the solr interface in Primary - Replica server architecture. It contains a connection to a Primary server used for writing data, and a connection to a Replica server used for reading data.

func (*PRClient) BatchCreate

func (c *PRClient) BatchCreate(ctx context.Context, items interface{}, opts *WriteOptions) (*Response, error)

BatchCreate ...

func (*PRClient) BatchGet

func (c *PRClient) BatchGet(ctx context.Context, ids []string, filter string) (*Response, error)

BatchGet ...

func (*PRClient) Clear

func (c *PRClient) Clear(ctx context.Context) (*Response, error)

Clear ...

func (*PRClient) Commit

func (c *PRClient) Commit(ctx context.Context, opts *CommitOptions) (*Response, error)

Commit ...

func (*PRClient) Create

func (c *PRClient) Create(ctx context.Context, item interface{}, opts *WriteOptions) (*Response, error)

Create ...

func (*PRClient) CustomUpdate

func (c *PRClient) CustomUpdate(ctx context.Context, item *UpdateBuilder, opts *WriteOptions) (*Response, error)

CustomUpdate ...

func (*PRClient) DeleteByID

func (c *PRClient) DeleteByID(ctx context.Context, id string, opts *WriteOptions) (*Response, error)

DeleteByID ...

func (*PRClient) DeleteByQuery

func (c *PRClient) DeleteByQuery(ctx context.Context, query string, opts *WriteOptions) (*Response, error)

DeleteByQuery ...

func (*PRClient) Get

func (c *PRClient) Get(ctx context.Context, id, filter string) (*Response, error)

Get ...

func (*PRClient) Optimize

func (c *PRClient) Optimize(ctx context.Context, opts *OptimizeOptions) (*Response, error)

Optimize ...

func (*PRClient) Ping

func (c *PRClient) Ping(ctx context.Context) error

Ping tests the connectivity of both servers

func (*PRClient) Rollback

func (c *PRClient) Rollback(ctx context.Context) (*Response, error)

Rollback ...

func (*PRClient) Search

func (c *PRClient) Search(ctx context.Context, q *Query) (*Response, error)

Search ...

func (*PRClient) SetBasicAuth

func (c *PRClient) SetBasicAuth(username, password string)

SetBasicAuth sets auth credentials if needed.

func (*PRClient) Update

func (c *PRClient) Update(ctx context.Context, item *UpdatedFields, opts *WriteOptions) (*Response, error)

Update ...

type Pivot

type Pivot struct {
	Field   string            `json:"field"`
	Value   interface{}       `json:"value"`
	Count   int               `json:"count"`
	Pivot   []*Pivot          `json:"pivot"`
	Stats   *Stats            `json:"stats"`
	Queries map[string]int    `json:"queries"`
	Ranges  map[string]*Range `json:"ranges"`
}

Pivot contains pivot faceting results. More info: https://lucene.apache.org/solr/guide/8_5/faceting.html#pivot-decision-tree-faceting

type Query

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

Query represents the query parameters of a search. It provides helper methods for most of the available solr query params.

func NewQuery

func NewQuery(opts *ReadOptions) *Query

NewQuery returns an initialized Query. It accepts as options a result rows limit and a debug type. It sets by default the return type to JSON, as it is the only type supported by this library.

func (*Query) AddFacet

func (q *Query) AddFacet(f *Facet)

AddFacet adds a facet to the query, along with field specific options. Not all options are supported, but functions like AddParam, SetParam can help with those missing options. More info: https://lucene.apache.org/solr/guide/8_5/faceting.html

func (*Query) AddFacetPivot

func (q *Query) AddFacetPivot(fieldsString string, minCount int)

AddFacetPivot adds a facet pivot. The given fieldsString should contain the fields to be faceted separated with a comma. The minCount parameter defines the minimum number of documents that need to match in order for the facet to be included in the results. The default is 1. More info: https://lucene.apache.org/solr/guide/8_5/faceting.html#pivot-decision-tree-faceting

func (*Query) AddField

func (q *Query) AddField(value string)

AddField adds the given field to the returned field list. More info: https://lucene.apache.org/solr/guide/8_5/common-query-parameters.html#fl-field-list-parameter

func (*Query) AddFilter

func (q *Query) AddFilter(key, value string)

AddFilter adds a key-value pair on which to filter the query. More info: https://lucene.apache.org/solr/guide/8_5/common-query-parameters.html#fq-filter-query-parameter

func (*Query) AddParam

func (q *Query) AddParam(key, value string)

AddParam allows the addition of custom query parameters.

func (*Query) AddQuery

func (q *Query) AddQuery(field, value string)

AddQuery adds a key-value pair to the Q parameter and facilitates the formulation of simple boolean queries. The field can be an empty string in the case of text search or an existing qf parameter. Using this will overwrite any call to the `SetQuery` method. For complex logic use that instead

func (*Query) Collapse

func (q *Query) Collapse(params *CollapseParams) error

Collapse sets the Collapsing Query Parser post filter that groups documents according to the given parameters. More Info: https://lucene.apache.org/solr/guide/8_5/collapse-and-expand-results.html#collapsing-query-parser

func (*Query) DelParam

func (q *Query) DelParam(key string)

DelParam allows the deletion of query parameters.

func (*Query) DelQuery

func (q *Query) DelQuery()

DelQuery removes any Q parameters that have been added

func (*Query) Expand

func (q *Query) Expand(opts *ExpandOptions)

Expand sets the parameter than returns an expand component used to expand the groups that were collapsed by the Collapsing Query Parser. The optional params override the original query values More info: https://lucene.apache.org/solr/guide/8_5/collapse-and-expand-results.html#expand-component

func (*Query) Group

func (q *Query) Group(params *GroupParams) error

Group sets the grouping parameters for a query to facilitate result grouping. The GroupParams must be present with at least the field parameter filled. More info: https://lucene.apache.org/solr/guide/8_5/result-grouping.html

func (*Query) SetBoost

func (q *Query) SetBoost(value string)

SetBoost sets the boost param (eDisMax only) More info: https://lucene.apache.org/solr/guide/8_5/the-extended-dismax-query-parser.html#extended-dismax-parameters

func (*Query) SetBoostFunctions

func (q *Query) SetBoostFunctions(value string)

SetBoostFunctions sets the boost functions param (DisMax & eDisMax only) More info: https://lucene.apache.org/solr/guide/8_5/the-dismax-query-parser.html#bf-boost-functions-parameter

func (*Query) SetBoostQuery

func (q *Query) SetBoostQuery(value string)

SetBoostQuery sets the boost query param (DisMax & eDisMax only) More info: https://lucene.apache.org/solr/guide/8_5/the-dismax-query-parser.html#bq-boost-query-parameter

func (*Query) SetFilter

func (q *Query) SetFilter(value string)

SetFilter gives the option to set a filter allowing for more complex logic instead of a basic key-value check.

func (*Query) SetMinimumShouldMatch

func (q *Query) SetMinimumShouldMatch(value string)

SetMinimumShouldMatch sets the minimum params to match (DisMax & eDisMax only) More info: https://lucene.apache.org/solr/guide/8_5/the-dismax-query-parser.html#mm-minimum-should-match-parameter

func (*Query) SetOperationAND

func (q *Query) SetOperationAND()

SetOperationAND sets the operation for the Q parameter to AND (only when using `AddQuery`)

func (*Query) SetOperationOR

func (q *Query) SetOperationOR()

SetOperationOR sets the operation for the Q parameter to OR (only when using `AddQuery`)

func (*Query) SetParam

func (q *Query) SetParam(key, value string)

SetParam allows the setting of custom query parameters.

func (*Query) SetQuery

func (q *Query) SetQuery(value string)

SetQuery sets the Q parameter of the query.

func (*Query) SetQueryFields

func (q *Query) SetQueryFields(fields []string)

SetQueryFields sets the fields to search (DisMax & eDisMax only) More info: https://lucene.apache.org/solr/guide/8_5/the-dismax-query-parser.html#qf-query-fields-parameter

func (*Query) SetRows added in v1.4.0

func (q *Query) SetRows(value int)

SetRows sets the amount of rows to be returned from the query overwritting the default value lucene.apache.org/solr/guide/8_5/common-query-parameters.html#rows-parameter

func (*Query) SetSort

func (q *Query) SetSort(value string)

SetSort sets the way the results are sorted. It should be formatted using the following protocol "<field name> <direction>, <field name> <direction>,...​" More info: https://lucene.apache.org/solr/guide/8_5/common-query-parameters.html#sort-parameter

func (*Query) SetStart

func (q *Query) SetStart(value int)

SetStart enables setting the starting index for a search query. It can be used when the available results are more than the rows returned to fetch the remainder rows. More info: https://lucene.apache.org/solr/guide/8_5/common-query-parameters.html#start-parameter

func (*Query) SetUserFields

func (q *Query) SetUserFields(fields []string)

SetUserFields sets the fields a user is allowed to query (eDisMax only) More info: https://lucene.apache.org/solr/guide/8_5/the-extended-dismax-query-parser.html#extended-dismax-parameters

func (*Query) String

func (q *Query) String() string

String returns the string representation of the query.

type Range

type Range struct {
	Counts *FacetFields `json:"counts"`
	Gap    string       `json:"gap"`
	Start  time.Time    `json:"start"`
	End    time.Time    `json:"end"`
}

Range contains range faceting results. More info: https://lucene.apache.org/solr/guide/8_5/faceting.html#range-faceting

type ReadOptions

type ReadOptions struct {
	Debug   DebugType
	DefType DefType
	Rows    int
}

ReadOptions contains options for read actions. Those include: Debug: Sets the type of debugging for the request DefType: Sets the type of query parse to use (default: lucene) Rows: Sets the number of rows to return

type Response

type Response struct {
	Header      *ResponseHeader          `json:"responseHeader"`
	Data        *ResponseData            `json:"response"`
	Error       *ResponseError           `json:"error"`
	Debug       *map[string]interface{}  `json:"debug"`
	Doc         *Doc                     `json:"doc"`
	Status      *string                  `json:"status"`
	Expanded    map[string]*ResponseData `json:"expanded"`
	FacetCounts *FacetCounts             `json:"facet_counts"`
	Grouped     *Grouped                 `json:"grouped"`
	Schema      *ResponseSchema          `json:"schema"`
}

Response represents the response from the solr server. It usually contains Header information, the response data or an error in case of erroneous response. Also it can contain Debug information when requested, a single document (in the case of realtimeGet) or just a status (in the case of the Ping request)

type ResponseData

type ResponseData struct {
	NumFound int64    `json:"numFound"`
	Start    int64    `json:"start"`
	Docs     Docs     `json:"docs"`
	MaxScore MaxScore `json:"maxScore"`
}

ResponseData is populated on a successful response from the solr server. It contains the number of documents found, the starting index (in case of a search) as well as the documents found

type ResponseError

type ResponseError struct {
	Code    float64       `json:"code"`
	Message string        `json:"msg"`
	Meta    []string      `json:"metadata"`
	Details []ErrorDetail `json:"details"`
}

ResponseError is populated in the event the response from the solr server is erroneous. It contains the status code, a message and some metadata about the error's class

func (*ResponseError) Error

func (r *ResponseError) Error() string

func (*ResponseError) UnmarshalJSON added in v1.1.0

func (r *ResponseError) UnmarshalJSON(b []byte) error

UnmarshalJSON implements the unmarshaler interface

type ResponseHeader

type ResponseHeader struct {
	Status int64                   `json:"status"`
	QTime  int64                   `json:"QTime"`
	Params *map[string]interface{} `json:"params"`
}

ResponseHeader is populated on every response from the solr server unless explicitly omitted. It contains the request status code the time it took as well as the params for the search query when applicable

type ResponseSchema

type ResponseSchema struct {
	Name          string          `json:"name"`
	Version       float64         `json:"version"`
	UniqueKey     string          `json:"uniqueKey"`
	FieldTypes    []*FieldType    `json:"fieldTypes"`
	Fields        []*Field        `json:"fields"`
	CopyFields    []*CopyField    `json:"copyFields"`
	DynamicFields []*DynamicField `json:"dynamicFields"`
}

ResponseSchema is populated when using the Schema API to retrive schema information.

type RetryableConfig added in v1.3.3

type RetryableConfig struct {
	Timeout      time.Duration
	RetryWaitMin time.Duration
	RetryWaitMax time.Duration
	RetryMax     int
	NoLog        bool
}

type RetryableConnection added in v1.3.0

type RetryableConnection struct {
	Host     string
	Core     string
	Username string
	Password string
	Timeout  time.Duration
	// contains filtered or unexported fields
}

RetryableConnection implements the retryablehttp library from Hashicorp that allows making a http request multiple times with a set time in case of failure due to connectivity issues. This for example can be useful if your solr servers are being shutdown while a new one gets started, the request can continue trying allowing for the server to be replaced without dropping it.

func NewRetryableConnection added in v1.3.0

func NewRetryableConnection(host, core string, client *http.Client, conf *RetryableConfig) (*RetryableConnection, error)

NewRetryableConnection ...

type SchemaAPI

type SchemaAPI struct {
	Path string
	// contains filtered or unexported fields
}

SchemaAPI contains a connection to solr and the path to it.

func NewSchemaAPI

func NewSchemaAPI(ctx context.Context, host, core string, client *http.Client) (*SchemaAPI, error)

NewSchemaAPI returns a new schema API, creating a connection to solr using the provided http client and host, core info.

func (*SchemaAPI) AddCopyField

func (s *SchemaAPI) AddCopyField(ctx context.Context, cf *CopyField) (*Response, error)

AddCopyField adds a new copy field rule to your schema. Source and Destination are required. Destination is always a string so for ease of use, unlike with the json API it is not possible to copy a field to multiple destinations. A different copy field rule must be made for each. For more info: https://lucene.apache.org/solr/guide/8_5/schema-api.html#add-a-new-copy-field-rule

func (*SchemaAPI) AddDynamicField

func (s *SchemaAPI) AddDynamicField(ctx context.Context, df *DynamicField) (*Response, error)

AddDynamicField adds a new dynamic field rule to your schema. For more info: https://lucene.apache.org/solr/guide/8_5/schema-api.html#add-a-dynamic-field-rule

func (*SchemaAPI) AddField

func (s *SchemaAPI) AddField(ctx context.Context, fl *Field) (*Response, error)

AddField adds a new field definition to your schema. If a field with the same name exists an error is thrown. For more info: https://lucene.apache.org/solr/guide/8_5/schema-api.html#add-a-new-field

func (*SchemaAPI) AddFieldType

func (s *SchemaAPI) AddFieldType(ctx context.Context, ft *FieldType) (*Response, error)

AddFieldType adds a new field type to the schema. For more info: https://lucene.apache.org/solr/guide/8_5/schema-api.html#add-a-new-field-type

func (*SchemaAPI) DeleteCopyField

func (s *SchemaAPI) DeleteCopyField(ctx context.Context, source, dest string) (*Response, error)

DeleteCopyField deletes a copy field rule from your schema. If the copy field rule does not exist in the schema an error is thrown. For more info: https://lucene.apache.org/solr/guide/8_5/schema-api.html#delete-a-copy-field-rule

func (*SchemaAPI) DeleteDynamicField

func (s *SchemaAPI) DeleteDynamicField(ctx context.Context, name string) (*Response, error)

DeleteDynamicField deletes a dynamic field rule from your schema. If the dynamic field rule does not exist in the schema, or if the schema contains a copy field rule with a target or destination that matches only this dynamic field rule, an error is thrown. For more info: https://lucene.apache.org/solr/guide/8_5/schema-api.html#delete-a-dynamic-field-rule

func (*SchemaAPI) DeleteField

func (s *SchemaAPI) DeleteField(ctx context.Context, name string) (*Response, error)

DeleteField removes a field definition from your schema. If the field does not exist in the schema, or if the field is the source or destination of a copy field rule, an error is thrown. For more info: https://lucene.apache.org/solr/guide/8_5/schema-api.html#delete-a-field

func (*SchemaAPI) DeleteFieldType

func (s *SchemaAPI) DeleteFieldType(ctx context.Context, name string) (*Response, error)

DeleteFieldType removes a field type from your schema. If the field type does not exist in the schema, or if any field or dynamic field rule in the schema uses the field type, an error is thrown. For more info: https://lucene.apache.org/solr/guide/8_5/schema-api.html#delete-a-field-type

func (*SchemaAPI) ReplaceDynamicField

func (s *SchemaAPI) ReplaceDynamicField(ctx context.Context, df *DynamicField) (*Response, error)

ReplaceDynamicField replaces a dynamic field rule in your schema. Note that you must supply the full definition for a dynamic field rule - this command will not partially modify a dynamic field rule’s definition. If the dynamic field rule does not exist in the schema an error is thrown. For more info: https://lucene.apache.org/solr/guide/8_5/schema-api.html#replace-a-dynamic-field-rule

func (*SchemaAPI) ReplaceField

func (s *SchemaAPI) ReplaceField(ctx context.Context, fl *Field) (*Response, error)

ReplaceField replaces a field’s definition. Note that you must supply the full definition for a field - this command will not partially modify a field’s definition. If the field does not exist in the schema an error is thrown. For more info: https://lucene.apache.org/solr/guide/8_5/schema-api.html#replace-a-field

func (*SchemaAPI) ReplaceFieldType

func (s *SchemaAPI) ReplaceFieldType(ctx context.Context, ft *FieldType) (*Response, error)

ReplaceFieldType replaces a field type in your schema. Note that you must supply the full definition for a field type - this command will not partially modify a field type’s definition. If the field type does not exist in the schema an error is thrown. For more info: https://lucene.apache.org/solr/guide/8_5/schema-api.html#replace-a-field-type

func (*SchemaAPI) RetrieveCopyField

func (s *SchemaAPI) RetrieveCopyField(ctx context.Context, source, dest string) (*CopyField, error)

RetrieveCopyField returns the specified copy field rule.

func (*SchemaAPI) RetrieveDynamicField

func (s *SchemaAPI) RetrieveDynamicField(ctx context.Context, name string) (*DynamicField, error)

RetrieveDynamicField returns the specified dynamic field.

func (*SchemaAPI) RetrieveField

func (s *SchemaAPI) RetrieveField(ctx context.Context, name string) (*Field, error)

RetrieveField returns the specified field.

func (*SchemaAPI) RetrieveFieldType

func (s *SchemaAPI) RetrieveFieldType(ctx context.Context, name string) (*FieldType, error)

RetrieveFieldType returns the specified field type.

func (*SchemaAPI) RetrieveSchema

func (s *SchemaAPI) RetrieveSchema(ctx context.Context) (*Response, error)

RetrieveSchema allows you to read how your schema has been defined. The output will include all fields, field types, dynamic rules and copy field rules in json. The schema name and version are also included.

func (*SchemaAPI) SetBasicAuth

func (s *SchemaAPI) SetBasicAuth(username, password string)

SetBasicAuth sets the authentication credentials if needed.

type SchemaCommand

type SchemaCommand string

SchemaCommand is used to restrict the available update commands that can be included in the body of a s.conn.request to the `/update` endpoint.

const (
	SchemaCommandAddField            SchemaCommand = "add-field"
	SchemaCommandDeleteField         SchemaCommand = "delete-field"
	SchemaCommandReplaceField        SchemaCommand = "replace-field"
	SchemaCommandAddDynamicField     SchemaCommand = "add-dynamic-field"
	SchemaCommandDeleteDynamicField  SchemaCommand = "delete-dynamic-field"
	SchemaCommandReplaceDynamicField SchemaCommand = "replace-dynamic-field"
	SchemaCommandAddFieldType        SchemaCommand = "add-field-type"
	SchemaCommandDeleteFieldType     SchemaCommand = "delete-field-type"
	SchemaCommandReplaceFieldType    SchemaCommand = "replace-field-type"
	SchemaCommandAddCopyField        SchemaCommand = "add-copy-field"
	SchemaCommandDeleteCopyField     SchemaCommand = "delete-copy-field"
)

Valid commands for the schema API

func (SchemaCommand) String

func (c SchemaCommand) String() string

type SingleClient

type SingleClient struct {
	BasePath string
	// contains filtered or unexported fields
}

SingleClient implements the solr interface and is the basic connection to a solr server.

func (*SingleClient) BatchCreate

func (c *SingleClient) BatchCreate(ctx context.Context, items interface{}, opts *WriteOptions) (*Response, error)

BatchCreate ...

func (*SingleClient) BatchGet

func (c *SingleClient) BatchGet(ctx context.Context, ids []string, filter string) (*Response, error)

BatchGet ...

func (*SingleClient) Clear

func (c *SingleClient) Clear(ctx context.Context) (*Response, error)

Clear ...

func (*SingleClient) Commit

func (c *SingleClient) Commit(ctx context.Context, opts *CommitOptions) (*Response, error)

Commit ...

func (*SingleClient) Create

func (c *SingleClient) Create(ctx context.Context, item interface{}, opts *WriteOptions) (*Response, error)

Create ...

func (*SingleClient) CustomUpdate

func (c *SingleClient) CustomUpdate(ctx context.Context, item *UpdateBuilder, opts *WriteOptions) (*Response, error)

CustomUpdate ...

func (*SingleClient) DeleteByID

func (c *SingleClient) DeleteByID(ctx context.Context, id string, opts *WriteOptions) (*Response, error)

DeleteByID ...

func (*SingleClient) DeleteByQuery

func (c *SingleClient) DeleteByQuery(ctx context.Context, query string, opts *WriteOptions) (*Response, error)

DeleteByQuery ...

func (*SingleClient) Get

func (c *SingleClient) Get(ctx context.Context, id, filter string) (*Response, error)

Get ...

func (*SingleClient) Optimize

func (c *SingleClient) Optimize(ctx context.Context, opts *OptimizeOptions) (*Response, error)

Optimize ...

func (*SingleClient) Ping

func (c *SingleClient) Ping(ctx context.Context) error

Ping ...

func (*SingleClient) Rollback

func (c *SingleClient) Rollback(ctx context.Context) (*Response, error)

Rollback ...

func (*SingleClient) Search

func (c *SingleClient) Search(ctx context.Context, q *Query) (*Response, error)

Search ...

func (*SingleClient) SetBasicAuth

func (c *SingleClient) SetBasicAuth(username, password string)

SetBasicAuth sets auth credentials if needed.

func (*SingleClient) Update

func (c *SingleClient) Update(ctx context.Context, item *UpdatedFields, opts *WriteOptions) (*Response, error)

Update ...

type Stats

type Stats struct {
	Fields map[string]interface{} `json:"stats_fields"`
}

Stats containts the results of stats when requested during pivot faceting.

type SynonymInitArgs added in v1.1.0

type SynonymInitArgs struct {
	IgnoreCase bool `json:"ignoreCase"`
}

SynonymInitArgs are the initialization arguments for a synonyms managed list.

type SynonymMappings added in v1.1.0

type SynonymMappings struct {
	InitArgs   *SynonymInitArgs    `json:"initArgs"`
	InitOn     time.Time           `json:"initializedOn"`
	UpdatedOn  time.Time           `json:"updatedSinceInit"`
	ManagedMap map[string][]string `json:"managedMap"`
}

SynonymMappings is a helper struct for navigating a synonyms managed list.

type UpdateBuilder

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

UpdateBuilder is a helper struct that provides methods to easily populate the body of a custom `/update` request

func NewUpdateBuilder

func NewUpdateBuilder() *UpdateBuilder

NewUpdateBuilder returns an initialized UpdateBuilder, a helper struct that provides methods to easily populate a custom request to the `/update` endpoint of the solr server, that can contain more than one action. Multiple additions or deletion are grouped in an array when sent to solr instead of a map (as seen in solr docs) for obvious reasons. Therefore actual action hierarchy CANNOT be achieved! It's usage is suggested for any cases that the methods provided by the Client does not cover. More info: https://lucene.apache.org/solr/guide/8_5/uploading-data-with-index-handlers.html#sending-json-update-commands

func (*UpdateBuilder) Add

func (b *UpdateBuilder) Add(item interface{})

Add inserts an add command block to the body. The provided input must be valid JSON. For atomic or in-place updates it is recommended to use the `Update` method that is provided by the Client interface.

func (*UpdateBuilder) DeleteByID added in v1.2.0

func (b *UpdateBuilder) DeleteByID(id string)

DeleteByID inserts a delete command block to the body. It should contain a document identifying the id (uniqueKey field)

func (*UpdateBuilder) DeleteByQuery added in v1.2.0

func (b *UpdateBuilder) DeleteByQuery(query string)

DeleteByQuery inserts a delete command block to the body. It should contain a document identifying a query to properly work.

type UpdatedFields

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

UpdatedFields is a helper struct that contains the fields to be updated during an atomic/in-place update. It provides methods that allow to easily create a document to be sent to the `/update` endpoint using the Client's `Update` method

func NewUpdateDocument

func NewUpdateDocument(id string) *UpdatedFields

NewUpdateDocument returns an UpdatedFields helper that is used to provided the fields to be updated in an atomic/in-place update. It requires as input the id (uniqueKey field) of the document to be updated in order for the update to be successful, if the id provided does not exist a new document will be created. More info: https://lucene.apache.org/solr/guide/8_5/updating-parts-of-documents.html

func (*UpdatedFields) Add

func (f *UpdatedFields) Add(key string, val interface{})

Add adds the specified value(s) to a multiValue field. Takes as input a key which is the field name and a val which is the provided value(s) to add.

func (*UpdatedFields) AddDistinct

func (f *UpdatedFields) AddDistinct(key string, val interface{})

AddDistinct adds the specified value(s) to a multiValue field only if they are not already present. Takes as input a key which is the field name and a val which is the provided value(s) to add.

func (*UpdatedFields) IncrementBy

func (f *UpdatedFields) IncrementBy(key string, val int)

IncrementBy increments a numeric value by a specific amount. Takes as input a key which is the field name and a val which is an int signifying the amount to increment by.

func (*UpdatedFields) Remove

func (f *UpdatedFields) Remove(key string, val interface{})

Remove removes the specified value(s) from a multiValue field. Takes as input a key which is the field name and a val which is the provided value(s) to remove.

func (*UpdatedFields) RemoveRegex

func (f *UpdatedFields) RemoveRegex(key string, val interface{})

RemoveRegex removes the specified regex(es) from a multiValue field. Takes as input a key which is the field name and a val which is the provided regex(es) to remove.

func (*UpdatedFields) Set

func (f *UpdatedFields) Set(key string, val interface{})

Set replaces or sets the field value(s) with the specified values(s). Takes as input a key which is the field name and a val which is the provided value(s) to set.

type UserData

type UserData struct {
	CommitCommandVersion string `json:"commitCommandVer"`
	CommitTimeMSec       string `json:"commitTimeMSec"`
}

UserData contains information about commits.

type WriteOptions

type WriteOptions struct {
	Commit         bool
	CommitWithin   int64
	AllowDuplicate bool
}

WriteOptions contains options for write actions. Those include: Commit: Autocommit all changes alongside the current request CommitWithin: Autocommit all changes after the specified time (in miliseconds) AllowDuplicate: Allows uniqueKey duplication

Directories

Path Synopsis
coreadmin command
customupdate command
managed command
query command
schema command
update command

Jump to

Keyboard shortcuts

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