XU XUv0.16.0

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

导入方式: elasticsearch #github.com/xulang-org/packages/elasticsearch

公开 API: 4 函数, 25 方法, 5 类型, 0 常量, 0 方法集

扩展包 `elasticsearch #github.com/xulang-org/packages/elasticsearch`,由模块 github.com/xulang-org/packages 提供。

github.com/xulang-org/packages · 1.17.2 · 安装与使用

示例代码 · API 声明

示例代码

以下源码来自官方 examples 仓库,可复制或下载。请在完整工程中使用本地 Xu SDK 运行;网络、数据库和桌面示例需要对应的服务或资源。

26_standalone_elasticsearch/main.xu

所需 SDK:Xu 0.8.3 · 完整工程 · 下载源码

Xu本地 SDK 示例
@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 声明

open

XuAPI
pub fn open(endpoint string) Client

用途

打开资源或建立网络连接。

参数

endpoint string
endpoint(string)

返回值

Client — 该类型的值

查看用法示例

open_pool

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

用途

执行 open pool 操作。

参数

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

返回值

Pool — 该类型的值

查看用法示例

struct Response

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

用途

Elasticsearch 服务端响应结果,包含状态码、响应头与正文数据。

公开字段

status_code int
字段(int)
body string
正文

struct Client

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

用途

Elasticsearch 客户端会话实例,维护与服务端的连接并提供操作接口。

公开字段

host string
主机
port int
端口
secure bool
字段(bool)

new_client

XuAPI
pub fn new_client(endpoint string) Client

用途

构造 client。

参数

endpoint string
endpoint(string)

返回值

Client — 该类型的值

($&Client) request

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

用途

$&Client 上的操作:请求。失败时抛出错误,调用方需处理或继续传播。

参数

c $&Client
本次调用使用的 Client 实例;以独占借用传入,方法可修改它,调用方仍持有实例。
method string
method(string)
path string
文件系统路径(string)
body string
正文(string)

返回值

Response — 该类型的值

($&Client) ping

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

用途

发送心跳保活探测请求,检测连接活性与服务可用性。

参数

c $&Client
本次调用使用的 Client 实例;以独占借用传入,方法可修改它,调用方仍持有实例。

返回值

bool — 是否成立

($&Client) info

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

用途

在 $&Client 上执行 info 操作。失败时抛出错误,调用方需处理或继续传播。

参数

c $&Client
本次调用使用的 Client 实例;以独占借用传入,方法可修改它,调用方仍持有实例。

返回值

string — 结果字符串

($&Client) index_doc

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

用途

$&Client 上的操作:执行 index doc 操作。失败时抛出错误,调用方需处理或继续传播。

参数

c $&Client
本次调用使用的 Client 实例;以独占借用传入,方法可修改它,调用方仍持有实例。
index string
index(string)
id string
id(string)
doc_json string
doc_json(string)

返回值

string — 结果字符串

($&Client) get_doc

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

用途

$&Client 上的操作:读取 doc。失败时抛出错误,调用方需处理或继续传播。

参数

c $&Client
本次调用使用的 Client 实例;以独占借用传入,方法可修改它,调用方仍持有实例。
index string
index(string)
id string
id(string)

返回值

string — 结果字符串

($&Client) delete_doc

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

用途

$&Client 上的操作:执行 delete doc 操作。失败时抛出错误,调用方需处理或继续传播。

参数

c $&Client
本次调用使用的 Client 实例;以独占借用传入,方法可修改它,调用方仍持有实例。
index string
index(string)
id string
id(string)

返回值

bool — 是否成立

($&Client) update_doc

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

用途

$&Client 上的操作:执行 update doc 操作。失败时抛出错误,调用方需处理或继续传播。

参数

c $&Client
本次调用使用的 Client 实例;以独占借用传入,方法可修改它,调用方仍持有实例。
index string
index(string)
id string
id(string)
doc_json string
doc_json(string)

返回值

bool — 是否成立

($&Client) create_index

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

用途

$&Client 上的操作:创建下标。失败时抛出错误,调用方需处理或继续传播。

参数

c $&Client
本次调用使用的 Client 实例;以独占借用传入,方法可修改它,调用方仍持有实例。
index string
index(string)
mapping_json string
mapping_json(string)

返回值

bool — 是否成立

($&Client) delete_index

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

用途

$&Client 上的操作:删除下标。失败时抛出错误,调用方需处理或继续传播。

参数

c $&Client
本次调用使用的 Client 实例;以独占借用传入,方法可修改它,调用方仍持有实例。
index string
index(string)

返回值

bool — 是否成立

($&Client) index_exists

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

用途

$&Client 上的操作:执行 index exists 操作。

参数

c $&Client
本次调用使用的 Client 实例;以独占借用传入,方法可修改它,调用方仍持有实例。
index string
index(string)

返回值

bool — 是否成立

($&Client) refresh

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

用途

在 $&Client 上执行 refresh 操作。失败时抛出错误,调用方需处理或继续传播。

参数

c $&Client
本次调用使用的 Client 实例;以独占借用传入,方法可修改它,调用方仍持有实例。
index string
index(string)

返回值

bool — 是否成立

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
}

用途

Elasticsearch & OpenSearch 连接池管理器。

公开字段

host string
主机
port int
端口
secure bool
字段(bool)
endpoint string
字段(string)
state chan pool.State
字段(通道;类型 chan pool.State)
max_idle int
字段(int)

new_pool

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

用途

构造 pool。

参数

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

返回值

Pool — 该类型的值

(&Pool) get

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

用途

在 &Pool 上执行 get 操作。

参数

p &Pool
本次调用使用的 Pool 实例;以只读借用传入,调用方仍持有实例。

返回值

Client — 该类型的值

(&Pool) dup

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

用途

创建并返回持有独立状态或底层的副本对象。

参数

p &Pool
本次调用使用的 Pool 实例;以只读借用传入,调用方仍持有实例。

返回值

Pool — 该类型的值

(&Pool) get_conn

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

用途

&Pool 上的操作:读取 conn。

参数

p &Pool
本次调用使用的 Pool 实例;以只读借用传入,调用方仍持有实例。

返回值

int — 该类型的值

(&Pool) put_conn

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

用途

&Pool 上的操作:执行 put conn 操作。

参数

p &Pool
本次调用使用的 Pool 实例;以只读借用传入,调用方仍持有实例。
fd int
文件描述符(int)

返回值

不返回值。

(&Pool) discard_conn

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

用途

&Pool 上的操作:丢弃连接。

参数

p &Pool
本次调用使用的 Pool 实例;以只读借用传入,调用方仍持有实例。
fd int
文件描述符(int)

返回值

不返回值。

(&Pool) search_match

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

用途

&Pool 上的操作:执行 search match 操作。失败时抛出错误,调用方需处理或继续传播。

参数

p &Pool
本次调用使用的 Pool 实例;以只读借用传入,调用方仍持有实例。
index string
index(string)
field string
field(string)
query_text string
query_text(string)

返回值

SearchResult — 该类型的值

(&Pool) get_doc

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

用途

&Pool 上的操作:读取 doc。失败时抛出错误,调用方需处理或继续传播。

参数

p &Pool
本次调用使用的 Pool 实例;以只读借用传入,调用方仍持有实例。
index string
index(string)
id string
id(string)

返回值

string — 结果字符串

(&Pool) index_doc

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

用途

&Pool 上的操作:执行 index doc 操作。失败时抛出错误,调用方需处理或继续传播。

参数

p &Pool
本次调用使用的 Pool 实例;以只读借用传入,调用方仍持有实例。
index string
index(string)
id string
id(string)
doc_json string
doc_json(string)

返回值

string — 结果字符串

(&Pool) delete_doc

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

用途

&Pool 上的操作:执行 delete doc 操作。失败时抛出错误,调用方需处理或继续传播。

参数

p &Pool
本次调用使用的 Pool 实例;以只读借用传入,调用方仍持有实例。
index string
index(string)
id string
id(string)

返回值

bool — 是否成立

(&Pool) ping

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

用途

发送心跳保活探测请求,检测连接活性与服务可用性。

参数

p &Pool
本次调用使用的 Pool 实例;以只读借用传入,调用方仍持有实例。

返回值

bool — 是否成立

(&Pool) close

XuAPI
pub fn (p &Pool) close()

用途

&Pool 上的操作:关闭资源。

参数

p &Pool
本次调用使用的 Pool 实例;以只读借用传入,调用方仍持有实例。

返回值

不返回值。

struct SearchHit

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

用途

承载 id、score、source 等属性的结构体。

公开字段

id string
字段(string)
score string
字段(string)
source string
字段(string)

struct SearchResult

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

用途

承载 total、raw_json、hits 等属性的结构体。

公开字段

total int
字段(int)
raw_json string
字段(string)
hits []SearchHit
字段([]SearchHit)

($&Client) search_match

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

用途

$&Client 上的操作:执行 search match 操作。失败时抛出错误,调用方需处理或继续传播。

参数

c $&Client
本次调用使用的 Client 实例;以独占借用传入,方法可修改它,调用方仍持有实例。
index string
index(string)
field string
field(string)
query_text string
query_text(string)

返回值

SearchResult — 该类型的值