open
pub fn open(endpoint string) ClientPurpose
Open resource or establish connection.
Parameters
endpointstring- endpoint (string)
Returns
Client — a value of this type
#github.com/xulang-org/packages/elasticsearchElasticsearch / 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
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@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) ClientOpen resource or establish connection.
endpoint stringClient — a value of this type
open_poolpub fn open_pool(endpoint string, max_idle int) PoolOpen pool.
endpoint stringmax_idle intPool — a value of this type
struct Responsepub struct Response {
pub status_code int
pub body string
}Elasticsearch Server response payload containing status, headers, and body.
status_code intbody stringstruct Clientpub struct Client {
pub host string
pub port int
pub secure bool
}Elasticsearch Client session maintaining connection and operations.
host stringport intsecure boolnew_clientpub fn new_client(endpoint string) ClientConstruct client.
endpoint stringClient — a value of this type
($&Client) requestpub fn (c $&Client) request(method string, path string, body string) ResponseExecute request on $&Client. Throws on failure; handle the error or propagate it to the caller.
c $&ClientClient instance used by this call (exclusive borrow).method stringpath stringbody stringResponse — a value of this type
($&Client) pingpub fn (c $&Client) ping() boolSend a ping heartbeat request to verify connection liveness.
c $&ClientClient instance used by this call (exclusive borrow).bool — true or false
($&Client) infopub fn (c $&Client) info() stringExecute info on $&Client. Throws on failure; handle the error or propagate it to the caller.
c $&ClientClient instance used by this call (exclusive borrow).string — result string
($&Client) index_docpub fn (c $&Client) index_doc(index string, id string, doc_json string) stringOperation on $&Client: index doc. Throws on failure; handle the error or propagate it to the caller.
c $&ClientClient instance used by this call (exclusive borrow).index stringid stringdoc_json stringstring — result string
($&Client) get_docpub fn (c $&Client) get_doc(index string, id string) stringOperation on $&Client: read doc. Throws on failure; handle the error or propagate it to the caller.
c $&ClientClient instance used by this call (exclusive borrow).index stringid stringstring — result string
($&Client) delete_docpub fn (c $&Client) delete_doc(index string, id string) boolOperation on $&Client: delete doc. Throws on failure; handle the error or propagate it to the caller.
c $&ClientClient instance used by this call (exclusive borrow).index stringid stringbool — true or false
($&Client) update_docpub fn (c $&Client) update_doc(index string, id string, doc_json string) boolOperation on $&Client: update doc. Throws on failure; handle the error or propagate it to the caller.
c $&ClientClient instance used by this call (exclusive borrow).index stringid stringdoc_json stringbool — true or false
($&Client) create_indexpub fn (c $&Client) create_index(index string, mapping_json string) boolOperation on $&Client: create index. Throws on failure; handle the error or propagate it to the caller.
c $&ClientClient instance used by this call (exclusive borrow).index stringmapping_json stringbool — true or false
($&Client) delete_indexpub fn (c $&Client) delete_index(index string) boolOperation on $&Client: delete index. Throws on failure; handle the error or propagate it to the caller.
c $&ClientClient instance used by this call (exclusive borrow).index stringbool — true or false
($&Client) index_existspub fn (c $&Client) index_exists(index string) boolOperation on $&Client: index exists.
c $&ClientClient instance used by this call (exclusive borrow).index stringbool — true or false
($&Client) refreshpub fn (c $&Client) refresh(index string) boolExecute refresh on $&Client. Throws on failure; handle the error or propagate it to the caller.
c $&ClientClient instance used by this call (exclusive borrow).index stringbool — true or false
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
}Connection Pool for Elasticsearch & OpenSearch. Manages reusable TCP/HTTP socket connections.
host stringport intsecure boolendpoint stringstate chan pool.Statemax_idle intnew_poolpub fn new_pool(endpoint string, max_idle int) PoolConstruct pool.
endpoint stringmax_idle intPool — a value of this type
(&Pool) getpub fn (p &Pool) get() ClientExecute get on &Pool.
p &PoolPool instance used by this call (borrow).Client — a value of this type
(&Pool) duppub fn (p &Pool) dup() PoolShares sockets and close state; clones configuration strings.
p &PoolPool instance used by this call (borrow).Pool — a value of this type
(&Pool) get_connpub fn (p &Pool) get_conn() intOperation on &Pool: read conn.
p &PoolPool instance used by this call (borrow).int — a value of this type
(&Pool) put_connpub fn (p &Pool) put_conn(fd int)Operation on &Pool: put connection.
p &PoolPool instance used by this call (borrow).fd intThis call does not return a value.
(&Pool) discard_connpub fn (p &Pool) discard_conn(fd int)Operation on &Pool: discard connection.
p &PoolPool instance used by this call (borrow).fd intThis call does not return a value.
(&Pool) searchpub fn (p &Pool) search(index string, query_dsl string) SearchResultOperation on &Pool: binary search. Throws on failure; handle the error or propagate it to the caller.
p &PoolPool instance used by this call (borrow).index stringquery_dsl stringSearchResult — a value of this type
(&Pool) search_matchpub fn (p &Pool) search_match(index string, field string, query_text string) SearchResultOperation on &Pool: binary search match. Throws on failure; handle the error or propagate it to the caller.
p &PoolPool instance used by this call (borrow).index stringfield stringquery_text stringSearchResult — a value of this type
(&Pool) get_docpub fn (p &Pool) get_doc(index string, id string) stringOperation on &Pool: read doc. Throws on failure; handle the error or propagate it to the caller.
p &PoolPool instance used by this call (borrow).index stringid stringstring — result string
(&Pool) index_docpub fn (p &Pool) index_doc(index string, id string, doc_json string) stringOperation on &Pool: index doc. Throws on failure; handle the error or propagate it to the caller.
p &PoolPool instance used by this call (borrow).index stringid stringdoc_json stringstring — result string
(&Pool) delete_docpub fn (p &Pool) delete_doc(index string, id string) boolOperation on &Pool: delete doc. Throws on failure; handle the error or propagate it to the caller.
p &PoolPool instance used by this call (borrow).index stringid stringbool — true or false
(&Pool) pingpub fn (p &Pool) ping() boolSend a ping heartbeat request to verify connection liveness.
p &PoolPool instance used by this call (borrow).bool — true or false
(&Pool) closepub fn (p &Pool) close()Operation on &Pool: close the resource.
p &PoolPool instance used by this call (borrow).This call does not return a value.
struct SearchHitpub struct SearchHit {
pub id string
pub score string
pub source string
}Structure encapsulating id, score, source.
id stringscore stringsource stringstruct SearchResultpub struct SearchResult {
pub total int
pub raw_json string
pub hits []SearchHit
}Structure encapsulating total, raw_json, hits.
total intraw_json stringhits []SearchHit($&Client) searchpub fn (c $&Client) search(index string, query_dsl string) SearchResultOperation on $&Client: binary search. Throws on failure; handle the error or propagate it to the caller.
c $&ClientClient instance used by this call (exclusive borrow).index stringquery_dsl stringSearchResult — a value of this type
($&Client) search_matchpub fn (c $&Client) search_match(index string, field string, query_text string) SearchResultOperation on $&Client: binary search match. Throws on failure; handle the error or propagate it to the caller.
c $&ClientClient instance used by this call (exclusive borrow).index stringfield stringquery_text stringSearchResult — a value of this type