elasticsearch

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jul 31, 2025 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

Package elasticsearch provides Elasticsearch client functionality with support for multiple versions. It implements a comprehensive interface for interacting with Elasticsearch clusters through the official Go client library.

Package elasticsearch defines types and structures used for Elasticsearch operations. It contains response types, request types, and utility types for the MCP server.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BulkItemResponse

type BulkItemResponse struct {
	Index   string `json:"_index"`
	Type    string `json:"_type"`
	ID      string `json:"_id"`
	Version int    `json:"_version"`
	Result  string `json:"result"`
	Status  int    `json:"status"`
	Error   *struct {
		Type   string `json:"type"`
		Reason string `json:"reason"`
	} `json:"error,omitempty"`
}

BulkItemResponse represents the response for a single item in a bulk operation

type BulkOperation

type BulkOperation struct {
	Operation string                 `json:"operation"`
	Index     string                 `json:"index"`
	Type      string                 `json:"type,omitempty"`
	ID        string                 `json:"id,omitempty"`
	Body      map[string]interface{} `json:"body,omitempty"`
}

BulkOperation represents a single operation in a bulk request

type BulkResponse

type BulkResponse struct {
	Took   int                           `json:"took"`
	Errors bool                          `json:"errors"`
	Items  []map[string]BulkItemResponse `json:"items"`
}

BulkResponse represents the response from bulk operations

type Client

type Client interface {
	Info(ctx context.Context) (*InfoResponse, error)
	Health(ctx context.Context) (*HealthResponse, error)

	CreateIndex(ctx context.Context, index string, body map[string]interface{}) error
	DeleteIndex(ctx context.Context, index string) error
	IndexExists(ctx context.Context, index string) (bool, error)
	ListIndices(ctx context.Context) ([]IndexInfo, error)

	Index(ctx context.Context, index, docID string, body map[string]interface{}) (*IndexResponse, error)
	Get(ctx context.Context, index, docID string) (*GetResponse, error)
	Delete(ctx context.Context, index, docID string) error
	Update(ctx context.Context, index, docID string, body map[string]interface{}) error

	Search(ctx context.Context, req *SearchRequest) (*SearchResponse, error)

	Bulk(ctx context.Context, operations []BulkOperation) (*BulkResponse, error)

	Close() error
}

Client defines the interface for Elasticsearch operations. It abstracts the underlying Elasticsearch client to provide a consistent API for all supported Elasticsearch versions (7, 8, 9).

func NewClient

func NewClient(cfg *config.ElasticsearchConfig, version string) (Client, error)

NewClient creates a new Elasticsearch client with the provided configuration. It configures authentication, SSL settings, and retry policies based on the config.

Parameters:

  • cfg: Elasticsearch configuration containing connection details
  • version: Target Elasticsearch version string

Returns:

  • Client: Configured Elasticsearch client interface
  • error: Any error that occurred during client creation

type ESClient

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

ESClient implements the Client interface using the official Elasticsearch Go client. It provides a concrete implementation that can work with Elasticsearch 7, 8, and 9.

func (*ESClient) Bulk

func (c *ESClient) Bulk(ctx context.Context, operations []BulkOperation) (*BulkResponse, error)

Bulk performs multiple operations in a single request. This is more efficient than individual operations for large datasets.

Parameters:

  • ctx: Context for request cancellation
  • operations: List of bulk operations to perform

Returns:

  • *BulkResponse: Results of all bulk operations
  • error: Any error that occurred during bulk operation

func (*ESClient) Close

func (c *ESClient) Close() error

Close gracefully closes the Elasticsearch client connection. Note: The official Elasticsearch Go client doesn't require explicit closing.

func (*ESClient) CreateIndex

func (c *ESClient) CreateIndex(ctx context.Context, index string, body map[string]interface{}) error

CreateIndex creates a new index in Elasticsearch with the specified configuration.

Parameters:

  • ctx: Context for request cancellation
  • index: Name of the index to create
  • body: Index configuration (mappings, settings, etc.)

func (*ESClient) Delete

func (c *ESClient) Delete(ctx context.Context, index, docID string) error

Delete removes a document from Elasticsearch.

Parameters:

  • ctx: Context for request cancellation
  • index: Name of the source index
  • docID: Document ID to delete

func (*ESClient) DeleteIndex

func (c *ESClient) DeleteIndex(ctx context.Context, index string) error

DeleteIndex removes an index from Elasticsearch.

Parameters:

  • ctx: Context for request cancellation
  • index: Name of the index to delete

func (*ESClient) Get

func (c *ESClient) Get(ctx context.Context, index, docID string) (*GetResponse, error)

Get retrieves a document from Elasticsearch by its ID.

Parameters:

  • ctx: Context for request cancellation
  • index: Name of the source index
  • docID: Document ID to retrieve

Returns:

  • *GetResponse: Response containing the document
  • error: Any error that occurred during retrieval

func (*ESClient) Health

func (c *ESClient) Health(ctx context.Context) (*HealthResponse, error)

Health retrieves the cluster health status from Elasticsearch. This provides information about cluster status, number of nodes, etc.

func (*ESClient) Index

func (c *ESClient) Index(ctx context.Context, index, docID string, body map[string]interface{}) (*IndexResponse, error)

Index adds or updates a document in Elasticsearch.

Parameters:

  • ctx: Context for request cancellation
  • index: Name of the target index
  • docID: Document ID (empty string for auto-generation)
  • body: Document content as a map

Returns:

  • *IndexResponse: Response containing operation details
  • error: Any error that occurred during indexing

func (*ESClient) IndexExists

func (c *ESClient) IndexExists(ctx context.Context, index string) (bool, error)

IndexExists checks whether an index exists in Elasticsearch.

Parameters:

  • ctx: Context for request cancellation
  • index: Name of the index to check

Returns:

  • bool: true if the index exists, false otherwise
  • error: Any error that occurred during the check

func (*ESClient) Info

func (c *ESClient) Info(ctx context.Context) (*InfoResponse, error)

Info retrieves cluster information from Elasticsearch. This includes cluster name, version, and other basic information.

func (*ESClient) ListIndices

func (c *ESClient) ListIndices(ctx context.Context) ([]IndexInfo, error)

ListIndices retrieves a list of all indices in the Elasticsearch cluster.

Returns:

  • []IndexInfo: List of index information
  • error: Any error that occurred during the operation

func (*ESClient) Search

func (c *ESClient) Search(ctx context.Context, req *SearchRequest) (*SearchResponse, error)

Search executes a search query against Elasticsearch.

Parameters:

  • ctx: Context for request cancellation
  • req: Search request containing query, index, pagination, etc.

Returns:

  • *SearchResponse: Search results with hits and metadata
  • error: Any error that occurred during search

func (*ESClient) Update

func (c *ESClient) Update(ctx context.Context, index, docID string, body map[string]interface{}) error

Update partially updates a document in Elasticsearch.

Parameters:

  • ctx: Context for request cancellation
  • index: Name of the target index
  • docID: Document ID to update
  • body: Partial document content for update

type GetResponse

type GetResponse struct {
	Index   string                 `json:"_index"`
	Type    string                 `json:"_type"`
	ID      string                 `json:"_id"`
	Version int                    `json:"_version"`
	SeqNo   int                    `json:"_seq_no"`
	Found   bool                   `json:"found"`
	Source  map[string]interface{} `json:"_source"`
}

GetResponse represents the response from document retrieval operations

type HealthResponse

type HealthResponse struct {
	ClusterName                 string  `json:"cluster_name"`
	Status                      string  `json:"status"`
	TimedOut                    bool    `json:"timed_out"`
	NumberOfNodes               int     `json:"number_of_nodes"`
	NumberOfDataNodes           int     `json:"number_of_data_nodes"`
	ActivePrimaryShards         int     `json:"active_primary_shards"`
	ActiveShards                int     `json:"active_shards"`
	RelocatingShards            int     `json:"relocating_shards"`
	InitializingShards          int     `json:"initializing_shards"`
	UnassignedShards            int     `json:"unassigned_shards"`
	DelayedUnassignedShards     int     `json:"delayed_unassigned_shards"`
	NumberOfPendingTasks        int     `json:"number_of_pending_tasks"`
	NumberOfInFlightFetch       int     `json:"number_of_in_flight_fetch"`
	TaskMaxWaitingInQueueMillis int     `json:"task_max_waiting_in_queue_millis"`
	ActiveShardsPercentAsNumber float64 `json:"active_shards_percent_as_number"`
}

HealthResponse represents the response from Elasticsearch cluster health API

type IndexInfo

type IndexInfo struct {
	Health       string `json:"health"`
	Status       string `json:"status"`
	Index        string `json:"index"`
	UUID         string `json:"uuid"`
	Pri          string `json:"pri"`
	Rep          string `json:"rep"`
	DocsCount    string `json:"docs.count"`
	DocsDeleted  string `json:"docs.deleted"`
	StoreSize    string `json:"store.size"`
	PriStoreSize string `json:"pri.store.size"`
}

IndexInfo contains information about an Elasticsearch index

type IndexResponse

type IndexResponse struct {
	Index   string `json:"_index"`
	Type    string `json:"_type"`
	ID      string `json:"_id"`
	Version int    `json:"_version"`
	Result  string `json:"result"`
	Shards  struct {
		Total      int `json:"total"`
		Successful int `json:"successful"`
		Failed     int `json:"failed"`
	} `json:"_shards"`
	SeqNo       int `json:"_seq_no"`
	PrimaryTerm int `json:"_primary_term"`
}

IndexResponse represents the response from document indexing operations

type InfoResponse

type InfoResponse struct {
	Name        string `json:"name"`
	ClusterName string `json:"cluster_name"`
	ClusterUUID string `json:"cluster_uuid"`
	Version     struct {
		Number                           string `json:"number"`
		BuildFlavor                      string `json:"build_flavor"`
		BuildType                        string `json:"build_type"`
		BuildHash                        string `json:"build_hash"`
		BuildDate                        string `json:"build_date"`
		BuildSnapshot                    bool   `json:"build_snapshot"`
		LuceneVersion                    string `json:"lucene_version"`
		MinimumWireCompatibilityVersion  string `json:"minimum_wire_compatibility_version"`
		MinimumIndexCompatibilityVersion string `json:"minimum_index_compatibility_version"`
	} `json:"version"`
	TagLine string `json:"tagline"`
}

InfoResponse represents the response from Elasticsearch cluster info API

type SearchHit

type SearchHit struct {
	Index  string                 `json:"_index"`
	Type   string                 `json:"_type"`
	ID     string                 `json:"_id"`
	Score  float64                `json:"_score"`
	Source map[string]interface{} `json:"_source"`
}

SearchHit represents a single search result

type SearchRequest

type SearchRequest struct {
	Index  string                 `json:"index,omitempty"`
	Query  map[string]interface{} `json:"query,omitempty"`
	Size   int                    `json:"size,omitempty"`
	From   int                    `json:"from,omitempty"`
	Sort   []interface{}          `json:"sort,omitempty"`
	Source interface{}            `json:"_source,omitempty"`
}

SearchRequest represents a search request to Elasticsearch

type SearchResponse

type SearchResponse struct {
	Took     int  `json:"took"`
	TimedOut bool `json:"timed_out"`
	Shards   struct {
		Total      int `json:"total"`
		Successful int `json:"successful"`
		Skipped    int `json:"skipped"`
		Failed     int `json:"failed"`
	} `json:"_shards"`
	Hits struct {
		Total struct {
			Value    int    `json:"value"`
			Relation string `json:"relation"`
		} `json:"total"`
		MaxScore float64     `json:"max_score"`
		Hits     []SearchHit `json:"hits"`
	} `json:"hits"`
}

SearchResponse represents the response from search operations

Jump to

Keyboard shortcuts

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