open
pub fn open(endpoint string) Client用途
打开资源或建立网络连接。
参数
endpointstring- endpoint(string)
返回值
Client — 该类型的值
#github.com/xulang-org/packages/elasticsearch扩展包 `elasticsearch #github.com/xulang-org/packages/elasticsearch`,由模块 github.com/xulang-org/packages 提供。
github.com/xulang-org/packages · 1.17.2 · 安装与使用
以下源码来自官方 examples 仓库,可复制或下载。请在完整工程中使用本地 Xu SDK 运行;网络、数据库和桌面示例需要对应的服务或资源。
26_standalone_elasticsearch/main.xu@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.")
}openpub fn open(endpoint string) Client打开资源或建立网络连接。
endpoint stringClient — 该类型的值
open_poolpub fn open_pool(endpoint string, max_idle int) Pool执行 open pool 操作。
endpoint stringmax_idle intPool — 该类型的值
struct Responsepub struct Response {
pub status_code int
pub body string
}Elasticsearch 服务端响应结果,包含状态码、响应头与正文数据。
status_code intbody stringstruct Clientpub struct Client {
pub host string
pub port int
pub secure bool
}Elasticsearch 客户端会话实例,维护与服务端的连接并提供操作接口。
host stringport intsecure boolnew_clientpub fn new_client(endpoint string) Client构造 client。
endpoint stringClient — 该类型的值
($&Client) requestpub fn (c $&Client) request(method string, path string, body string) Response$&Client 上的操作:请求。失败时抛出错误,调用方需处理或继续传播。
c $&ClientClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。method stringpath stringbody stringResponse — 该类型的值
($&Client) pingpub fn (c $&Client) ping() bool发送心跳保活探测请求,检测连接活性与服务可用性。
c $&ClientClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。bool — 是否成立
($&Client) infopub fn (c $&Client) info() string在 $&Client 上执行 info 操作。失败时抛出错误,调用方需处理或继续传播。
c $&ClientClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。string — 结果字符串
($&Client) index_docpub fn (c $&Client) index_doc(index string, id string, doc_json string) string$&Client 上的操作:执行 index doc 操作。失败时抛出错误,调用方需处理或继续传播。
c $&ClientClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。index stringid stringdoc_json stringstring — 结果字符串
($&Client) get_docpub fn (c $&Client) get_doc(index string, id string) string$&Client 上的操作:读取 doc。失败时抛出错误,调用方需处理或继续传播。
c $&ClientClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。index stringid stringstring — 结果字符串
($&Client) delete_docpub fn (c $&Client) delete_doc(index string, id string) bool$&Client 上的操作:执行 delete doc 操作。失败时抛出错误,调用方需处理或继续传播。
c $&ClientClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。index stringid stringbool — 是否成立
($&Client) update_docpub fn (c $&Client) update_doc(index string, id string, doc_json string) bool$&Client 上的操作:执行 update doc 操作。失败时抛出错误,调用方需处理或继续传播。
c $&ClientClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。index stringid stringdoc_json stringbool — 是否成立
($&Client) create_indexpub fn (c $&Client) create_index(index string, mapping_json string) bool$&Client 上的操作:创建下标。失败时抛出错误,调用方需处理或继续传播。
c $&ClientClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。index stringmapping_json stringbool — 是否成立
($&Client) delete_indexpub fn (c $&Client) delete_index(index string) bool$&Client 上的操作:删除下标。失败时抛出错误,调用方需处理或继续传播。
c $&ClientClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。index stringbool — 是否成立
($&Client) index_existspub fn (c $&Client) index_exists(index string) bool$&Client 上的操作:执行 index exists 操作。
c $&ClientClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。index stringbool — 是否成立
($&Client) refreshpub fn (c $&Client) refresh(index string) bool在 $&Client 上执行 refresh 操作。失败时抛出错误,调用方需处理或继续传播。
c $&ClientClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。index stringbool — 是否成立
struct Poolpub 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 stringport intsecure boolendpoint stringstate chan pool.Statemax_idle intnew_poolpub fn new_pool(endpoint string, max_idle int) Pool构造 pool。
endpoint stringmax_idle intPool — 该类型的值
(&Pool) getpub fn (p &Pool) get() Client在 &Pool 上执行 get 操作。
p &PoolPool 实例;以只读借用传入,调用方仍持有实例。Client — 该类型的值
(&Pool) duppub fn (p &Pool) dup() Pool创建并返回持有独立状态或底层的副本对象。
p &PoolPool 实例;以只读借用传入,调用方仍持有实例。Pool — 该类型的值
(&Pool) get_connpub fn (p &Pool) get_conn() int&Pool 上的操作:读取 conn。
p &PoolPool 实例;以只读借用传入,调用方仍持有实例。int — 该类型的值
(&Pool) put_connpub fn (p &Pool) put_conn(fd int)&Pool 上的操作:执行 put conn 操作。
p &PoolPool 实例;以只读借用传入,调用方仍持有实例。fd int不返回值。
(&Pool) discard_connpub fn (p &Pool) discard_conn(fd int)&Pool 上的操作:丢弃连接。
p &PoolPool 实例;以只读借用传入,调用方仍持有实例。fd int不返回值。
(&Pool) searchpub fn (p &Pool) search(index string, query_dsl string) SearchResult&Pool 上的操作:二分查找。失败时抛出错误,调用方需处理或继续传播。
p &PoolPool 实例;以只读借用传入,调用方仍持有实例。index stringquery_dsl stringSearchResult — 该类型的值
(&Pool) search_matchpub fn (p &Pool) search_match(index string, field string, query_text string) SearchResult&Pool 上的操作:执行 search match 操作。失败时抛出错误,调用方需处理或继续传播。
p &PoolPool 实例;以只读借用传入,调用方仍持有实例。index stringfield stringquery_text stringSearchResult — 该类型的值
(&Pool) get_docpub fn (p &Pool) get_doc(index string, id string) string&Pool 上的操作:读取 doc。失败时抛出错误,调用方需处理或继续传播。
p &PoolPool 实例;以只读借用传入,调用方仍持有实例。index stringid stringstring — 结果字符串
(&Pool) index_docpub fn (p &Pool) index_doc(index string, id string, doc_json string) string&Pool 上的操作:执行 index doc 操作。失败时抛出错误,调用方需处理或继续传播。
p &PoolPool 实例;以只读借用传入,调用方仍持有实例。index stringid stringdoc_json stringstring — 结果字符串
(&Pool) delete_docpub fn (p &Pool) delete_doc(index string, id string) bool&Pool 上的操作:执行 delete doc 操作。失败时抛出错误,调用方需处理或继续传播。
p &PoolPool 实例;以只读借用传入,调用方仍持有实例。index stringid stringbool — 是否成立
(&Pool) pingpub fn (p &Pool) ping() bool发送心跳保活探测请求,检测连接活性与服务可用性。
p &PoolPool 实例;以只读借用传入,调用方仍持有实例。bool — 是否成立
(&Pool) closepub fn (p &Pool) close()&Pool 上的操作:关闭资源。
p &PoolPool 实例;以只读借用传入,调用方仍持有实例。不返回值。
struct SearchHitpub struct SearchHit {
pub id string
pub score string
pub source string
}承载 id、score、source 等属性的结构体。
id stringscore stringsource stringstruct SearchResultpub struct SearchResult {
pub total int
pub raw_json string
pub hits []SearchHit
}承载 total、raw_json、hits 等属性的结构体。
total intraw_json stringhits []SearchHit($&Client) searchpub fn (c $&Client) search(index string, query_dsl string) SearchResult$&Client 上的操作:二分查找。失败时抛出错误,调用方需处理或继续传播。
c $&ClientClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。index stringquery_dsl stringSearchResult — 该类型的值
($&Client) search_matchpub fn (c $&Client) search_match(index string, field string, query_text string) SearchResult$&Client 上的操作:执行 search match 操作。失败时抛出错误,调用方需处理或继续传播。
c $&ClientClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。index stringfield stringquery_text stringSearchResult — 该类型的值