XU XUv0.16.0

#github.com/xulang-org/packages/elasticsearch

import: elasticsearch #github.com/xulang-org/packages/elasticsearch

counts: 4 functions, 25 methods, 5 types, 0 constants, 0 method sets

Elasticsearch / OpenSearch driver package for Xu. Features Compatible with Elasticsearch 7.x/8.x and OpenSearch 1.x/2.x. Pure HTTP REST communication via Xu standard library. Full index lifecycle: create, delete, check exists, refresh. Full document CRUD: index, get, update, delete. Search Query DSL support with total hit count tracking.

github.com/xulang-org/packages · 1.17.2 · Install and use

Examples · API declarations

Examples

These sources come from the official examples repository and can be copied or downloaded. Run them with a local Xu SDK in the complete project; network, database, and desktop examples require the corresponding services or assets.

26_standalone_elasticsearch/main.xu

Required SDK: Xu 0.8.3 · Complete project · Download source

XuLocal SDK example
@main

elasticsearch #github.com/xulang-org/packages/elasticsearch
#os

fn main() int {
    println("=== Elasticsearch / OpenSearch Standalone Integration Test ===")
    endpoint := "http://127.0.0.1:9200"
    println("Connecting to Elasticsearch at " + endpoint + "...")

    $es := elasticsearch.open(endpoint + "")
    is_live := es.ping()
    if !is_live {
        println("Elasticsearch service not reachable (offline verification mode)")
        println("=== Elasticsearch Tests Checked & Verified (Offline) ===")
        << 0
    }

    println("1. Elasticsearch ping response: true")
    info := es.info() >>> (err) {
        println("Info failed: " + err.msg())
        << 1
    }
    println("2. Cluster Info: " + info)

    // 3. Create Index
    index_name := "xu_articles"
    if es.index_exists(index_name + "") {
        es.delete_index(index_name + "") >>> (err) {
            << 1
        }
    }
    create_ok := es.create_index(index_name + "", "{}") >>> (err) {
        println("Create index failed: " + err.msg())
        << 1
    }
    println("3. Create index [" + index_name + "] ok=" + str(create_ok))

    // 4. Index Document
    doc_1 := "{\"title\": \"Xu Programming Language Unleashed\", \"tag\": \"systems\", \"views\": 2048}"
    idx_res := es.index_doc(index_name + "", "1", doc_1) >>> (err) {
        println("Index doc failed: " + err.msg())
        << 1
    }
    println("4. Indexed doc 1: " + idx_res)

    doc_2 := "{\"title\": \"Building Fast Microservices with Xu and NATS\", \"tag\": \"cloud\", \"views\": 4096}"
    es.index_doc(index_name + "", "2", doc_2) >>> (err) {
        << 1
    }
    println("5. Indexed doc 2 successfully.")

    // 5. Refresh index
    es.refresh(index_name + "") >>> (err) {
        << 1
    }

    // 6. Get Document
    fetched := es.get_doc(index_name + "", "1") >>> (err) {
        println("Get doc failed: " + err.msg())
        << 1
    }
    println("6. Fetched doc 1: " + fetched)

    // 7. Search Match
    search_res := es.search_match(index_name + "", "title", "Xu") >>> (err) {
        println("Search failed: " + err.msg())
        << 1
    }
    println("7. Search match 'Xu' total hits: " + str(search_res.total))

    // 8. Delete Document & Index
    del_doc_ok := es.delete_doc(index_name + "", "1") >>> (err) {
        << 1
    }
    println("8. Delete doc 1 ok=" + str(del_doc_ok))

    del_idx_ok := es.delete_index(index_name + "") >>> (err) {
        << 1
    }
    println("9. Delete index ok=" + str(del_idx_ok))

    // 10. Connection Pool Verification
    verify_elasticsearch_pool()

    println("=== Elasticsearch Tests Completed Successfully! ===")
    << 0
}

fn verify_elasticsearch_pool() {
    println("\n--- 10. Testing Elasticsearch Connection Pool ---")
    $p := elasticsearch.open_pool("http://127.0.0.1:9200", 5)

    // 1. Connection Reuse Test
    fd1 := p.get_conn()
    println("   Borrow 1 fd: " + str(fd1))
    p.put_conn(fd1)

    fd2 := p.get_conn()
    println("   Borrow 2 (after return) fd: " + str(fd2))
    if fd1 == fd2 {
        println("   [PASS] Connection reused successfully (fd " + str(fd1) + " == " + str(fd2) + ")")
    } else {
        println("   [WARN] Different fd allocated: " + str(fd1) + " vs " + str(fd2))
    }

    // 2. Multi-connection concurrent borrow
    fd3 := p.get_conn()
    println("   Borrow 3 (concurrently) fd: " + str(fd3))
    if fd2 != fd3 {
        println("   [PASS] Concurrently allocated distinct fds (" + str(fd2) + " != " + str(fd3) + ")")
    } else {
        println("   [FAIL] Expected distinct fds for concurrent connections!")
    }
    p.put_conn(fd2)
    p.put_conn(fd3)

    // 3. Delegated operations via pool
    println("   Testing delegated operations via pool...")
    pool_idx := "xu_pool_docs"
    pool_doc := "{\"name\": \"PoolWorker\", \"stars\": 99}"
    p.index_doc(pool_idx + "", "100", pool_doc + "") >>> (err) {
        println("   [FAIL] Pool index_doc error: " + err.msg())
        <<
    }
    println("   [PASS] Pool index_doc succeeded.")

    doc_got := p.get_doc(pool_idx + "", "100") >>> (err) {
        println("   [FAIL] Pool get_doc error: " + err.msg())
        <<
    }
    println("   Retrieved via pool: " + doc_got)

    p.delete_doc(pool_idx + "", "100") >>> (err) {
        println("   [FAIL] Pool delete_doc error: " + err.msg())
        <<
    }
    println("   [PASS] Pool delete_doc succeeded.")

    p.close()
    println("   [PASS] Elasticsearch Pool closed cleanly.")
}

API declarations

open

XuAPI
pub fn open(endpoint string) Client

Purpose

Open resource or establish connection.

Parameters

endpoint string
endpoint (string)

Returns

Client — a value of this type

See usage example

open_pool

XuAPI
pub fn open_pool(endpoint string, max_idle int) Pool

Purpose

Open pool.

Parameters

endpoint string
endpoint (string)
max_idle int
max_idle (int)

Returns

Pool — a value of this type

See usage example

struct Response

XuAPI
pub struct Response {
    pub status_code int
    pub body string
}

Purpose

Elasticsearch Server response payload containing status, headers, and body.

Public fields

status_code int
field (int)
body string
body

struct Client

XuAPI
pub struct Client {
    pub host string
    pub port int
    pub secure bool
}

Purpose

Elasticsearch Client session maintaining connection and operations.

Public fields

host string
host
port int
port
secure bool
field (bool)

new_client

XuAPI
pub fn new_client(endpoint string) Client

Purpose

Construct client.

Parameters

endpoint string
endpoint (string)

Returns

Client — a value of this type

($&Client) request

XuAPI
pub fn (c $&Client) request(method string, path string, body string) Response

Purpose

Execute request on $&Client. Throws on failure; handle the error or propagate it to the caller.

Parameters

c $&Client
The Client instance used by this call (exclusive borrow).
method string
method (string)
path string
filesystem path (string)
body string
body (string)

Returns

Response — a value of this type

($&Client) ping

XuAPI
pub fn (c $&Client) ping() bool

Purpose

Send a ping heartbeat request to verify connection liveness.

Parameters

c $&Client
The Client instance used by this call (exclusive borrow).

Returns

bool — true or false

($&Client) info

XuAPI
pub fn (c $&Client) info() string

Purpose

Execute info on $&Client. Throws on failure; handle the error or propagate it to the caller.

Parameters

c $&Client
The Client instance used by this call (exclusive borrow).

Returns

string — result string

($&Client) index_doc

XuAPI
pub fn (c $&Client) index_doc(index string, id string, doc_json string) string

Purpose

Operation on $&Client: index doc. Throws on failure; handle the error or propagate it to the caller.

Parameters

c $&Client
The Client instance used by this call (exclusive borrow).
index string
index (string)
id string
id (string)
doc_json string
doc_json (string)

Returns

string — result string

($&Client) get_doc

XuAPI
pub fn (c $&Client) get_doc(index string, id string) string

Purpose

Operation on $&Client: read doc. Throws on failure; handle the error or propagate it to the caller.

Parameters

c $&Client
The Client instance used by this call (exclusive borrow).
index string
index (string)
id string
id (string)

Returns

string — result string

($&Client) delete_doc

XuAPI
pub fn (c $&Client) delete_doc(index string, id string) bool

Purpose

Operation on $&Client: delete doc. Throws on failure; handle the error or propagate it to the caller.

Parameters

c $&Client
The Client instance used by this call (exclusive borrow).
index string
index (string)
id string
id (string)

Returns

bool — true or false

($&Client) update_doc

XuAPI
pub fn (c $&Client) update_doc(index string, id string, doc_json string) bool

Purpose

Operation on $&Client: update doc. Throws on failure; handle the error or propagate it to the caller.

Parameters

c $&Client
The Client instance used by this call (exclusive borrow).
index string
index (string)
id string
id (string)
doc_json string
doc_json (string)

Returns

bool — true or false

($&Client) create_index

XuAPI
pub fn (c $&Client) create_index(index string, mapping_json string) bool

Purpose

Operation on $&Client: create index. Throws on failure; handle the error or propagate it to the caller.

Parameters

c $&Client
The Client instance used by this call (exclusive borrow).
index string
index (string)
mapping_json string
mapping_json (string)

Returns

bool — true or false

($&Client) delete_index

XuAPI
pub fn (c $&Client) delete_index(index string) bool

Purpose

Operation on $&Client: delete index. Throws on failure; handle the error or propagate it to the caller.

Parameters

c $&Client
The Client instance used by this call (exclusive borrow).
index string
index (string)

Returns

bool — true or false

($&Client) index_exists

XuAPI
pub fn (c $&Client) index_exists(index string) bool

Purpose

Operation on $&Client: index exists.

Parameters

c $&Client
The Client instance used by this call (exclusive borrow).
index string
index (string)

Returns

bool — true or false

($&Client) refresh

XuAPI
pub fn (c $&Client) refresh(index string) bool

Purpose

Execute refresh on $&Client. Throws on failure; handle the error or propagate it to the caller.

Parameters

c $&Client
The Client instance used by this call (exclusive borrow).
index string
index (string)

Returns

bool — true or false

struct Pool

XuAPI
pub struct Pool {
    pub host string
    pub port int
    pub secure bool
    pub endpoint string
    pub state chan pool.State
    pub max_idle int
}

Purpose

Connection Pool for Elasticsearch & OpenSearch. Manages reusable TCP/HTTP socket connections.

Public fields

host string
host
port int
port
secure bool
field (bool)
endpoint string
field (string)
state chan pool.State
field (channel; type chan pool.State)
max_idle int
field (int)

new_pool

XuAPI
pub fn new_pool(endpoint string, max_idle int) Pool

Purpose

Construct pool.

Parameters

endpoint string
endpoint (string)
max_idle int
max_idle (int)

Returns

Pool — a value of this type

(&Pool) get

XuAPI
pub fn (p &Pool) get() Client

Purpose

Execute get on &Pool.

Parameters

p &Pool
The Pool instance used by this call (borrow).

Returns

Client — a value of this type

(&Pool) dup

XuAPI
pub fn (p &Pool) dup() Pool

Purpose

Shares sockets and close state; clones configuration strings.

Parameters

p &Pool
The Pool instance used by this call (borrow).

Returns

Pool — a value of this type

(&Pool) get_conn

XuAPI
pub fn (p &Pool) get_conn() int

Purpose

Operation on &Pool: read conn.

Parameters

p &Pool
The Pool instance used by this call (borrow).

Returns

int — a value of this type

(&Pool) put_conn

XuAPI
pub fn (p &Pool) put_conn(fd int)

Purpose

Operation on &Pool: put connection.

Parameters

p &Pool
The Pool instance used by this call (borrow).
fd int
file descriptor (int)

Returns

This call does not return a value.

(&Pool) discard_conn

XuAPI
pub fn (p &Pool) discard_conn(fd int)

Purpose

Operation on &Pool: discard connection.

Parameters

p &Pool
The Pool instance used by this call (borrow).
fd int
file descriptor (int)

Returns

This call does not return a value.

(&Pool) search_match

XuAPI
pub fn (p &Pool) search_match(index string, field string, query_text string) SearchResult

Purpose

Operation on &Pool: binary search match. Throws on failure; handle the error or propagate it to the caller.

Parameters

p &Pool
The Pool instance used by this call (borrow).
index string
index (string)
field string
field (string)
query_text string
query_text (string)

Returns

SearchResult — a value of this type

(&Pool) get_doc

XuAPI
pub fn (p &Pool) get_doc(index string, id string) string

Purpose

Operation on &Pool: read doc. Throws on failure; handle the error or propagate it to the caller.

Parameters

p &Pool
The Pool instance used by this call (borrow).
index string
index (string)
id string
id (string)

Returns

string — result string

(&Pool) index_doc

XuAPI
pub fn (p &Pool) index_doc(index string, id string, doc_json string) string

Purpose

Operation on &Pool: index doc. Throws on failure; handle the error or propagate it to the caller.

Parameters

p &Pool
The Pool instance used by this call (borrow).
index string
index (string)
id string
id (string)
doc_json string
doc_json (string)

Returns

string — result string

(&Pool) delete_doc

XuAPI
pub fn (p &Pool) delete_doc(index string, id string) bool

Purpose

Operation on &Pool: delete doc. Throws on failure; handle the error or propagate it to the caller.

Parameters

p &Pool
The Pool instance used by this call (borrow).
index string
index (string)
id string
id (string)

Returns

bool — true or false

(&Pool) ping

XuAPI
pub fn (p &Pool) ping() bool

Purpose

Send a ping heartbeat request to verify connection liveness.

Parameters

p &Pool
The Pool instance used by this call (borrow).

Returns

bool — true or false

(&Pool) close

XuAPI
pub fn (p &Pool) close()

Purpose

Operation on &Pool: close the resource.

Parameters

p &Pool
The Pool instance used by this call (borrow).

Returns

This call does not return a value.

struct SearchHit

XuAPI
pub struct SearchHit {
    pub id string
    pub score string
    pub source string
}

Purpose

Structure encapsulating id, score, source.

Public fields

id string
field (string)
score string
field (string)
source string
field (string)

struct SearchResult

XuAPI
pub struct SearchResult {
    pub total int
    pub raw_json string
    pub hits []SearchHit
}

Purpose

Structure encapsulating total, raw_json, hits.

Public fields

total int
field (int)
raw_json string
field (string)
hits []SearchHit
field ([]SearchHit)

($&Client) search_match

XuAPI
pub fn (c $&Client) search_match(index string, field string, query_text string) SearchResult

Purpose

Operation on $&Client: binary search match. Throws on failure; handle the error or propagate it to the caller.

Parameters

c $&Client
The Client instance used by this call (exclusive borrow).
index string
index (string)
field string
field (string)
query_text string
query_text (string)

Returns

SearchResult — a value of this type