Rust 初识及Rust的ESApi
Posted 双斜杠少年
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Rust 初识及Rust的ESApi相关的知识,希望对你有一定的参考价值。
Rust
Rust是一门系统编程语言 ,专注于安全 ,尤其是并发安全,支持函数式和命令式以及泛型等编程范式的多范式语言。Rust在语法上和C++类似 ,但是设计者想要在保证性能的同时提供更好的内存安全。
Rust致力于成为优雅解决高并发和高安全性系统问题的编程语言 [10] ,适用于大型场景,即创造维护能够保持大型系统完整的边界。这就导致了它强调安全,内存布局控制和并发的特点。
安装
curl https://sh.rustup.rs -sSf | sh
安装完成后,开始在idea 中配置rust 环境(后来发现cLion 编译器对 rust 支持更好,支持api智能提示)
然后新建rust 项目
概念特性
关于rust 的特性和概念,我也是初始。其中“所有权”概念和“生命周期”概念比较独特,可以多关心一下。
下面是一些我觉得比较好的文档 记录一下:
通过例子学 Rust
官方文档
github 指南
官网入口
仓库,类似maven的 mvnrepository 里面各种包的文档很详细
Es
最后贴上用rust 操作es的小 demo
use elasticsearch::auth::Credentials, Elasticsearch, Error, SearchParts, CreateParts;
use url::Url;
use serde_json::json, Value;
use elasticsearch::http::Method;
use elasticsearch::http::headers::HeaderMap;
///!默认链接
pub async fn get_client() -> Result<(), Box<dyn std::error::Error>>
let client = Elasticsearch::default();
let body = b"\\"query\\":\\"match_all\\":";
let response = client
.send(
Method::Post,
SearchParts::IndexType(&["user_index"], &["user"]).url().as_ref(),
HeaderMap::new(),
Option::<&Value>::None,
Some(body.as_ref()),
)
.await?;
let response_body = response.json::<Value>().await?;
let took = response_body["took"].as_i64().unwrap();
for hit in response_body["hits"]["hits"].as_array().unwrap()
println!(":?", hit["_source"]);
Ok(())
use elasticsearch::http::transport::SingleNodeConnectionPool, TransportBuilder;
///!包含验证信息的客户端链接
pub async fn get_client_credentials() -> Result<(), Box<dyn std::error::Error>>
let url = Url::parse("http://localhost:9200")?;
let conn_pool = SingleNodeConnectionPool::new(url);
let credentials = Credentials::Basic("".into(), "".into());
let transport = TransportBuilder::new(conn_pool).auth(credentials).build()?;
let client = Elasticsearch::new(transport);
let response = client
.search(SearchParts::IndexType(&["user_index"], &["user"]))
.from(0)
.size(10)
.body(json!(
"query":
"match_all":
))
.send()
.await?;
let response_body = response.json::<Value>().await?;
let took = response_body["took"].as_i64().unwrap();
for hit in response_body["hits"]["hits"].as_array().unwrap()
// print the source document
println!(":?", hit["_source"]);
Ok(())
///!保存数据
pub async fn put_data() -> Result<(), Box<dyn std::error::Error>>
let url = Url::parse("http://localhost:9200")?;
let conn_pool = SingleNodeConnectionPool::new(url);
let credentials = Credentials::Basic("".into(), "".into());
let transport = TransportBuilder::new(conn_pool).auth(credentials).build()?;
let client = Elasticsearch::new(transport);
let response = client.create(CreateParts::IndexTypeId("user_index", "user", "100001"))
.body(json!(
"id": "100001",
"user_name": "yang",
"mobile": "15683799234",
"birth": "1999-06-15",
"gender": "1",
"age": "26",
"height": "175",
"weight": "65",
"update_time": "2020-02-02 20:20:20"
)).send().await?;
let successful = response.status_code().is_success();
Ok(())
///!批量保存
pub async fn batch_save_portrait(maps: Vec<Map<String, Value>>) -> Result<(), Box<dyn std::error::Error>>
println!(",", "批量保存画像", maps.len());
let mut bodys: Vec<JsonBody<_>> = Vec::with_capacity(11000);
for map in maps
//保存到es 的 id,必须得传
bodys.push(json!("index": "_id": map.get("user_id")).into());
//map 为键值对 转化为 jsonBody
bodys.push(JsonBody::from(Value::Object(map)).into());
let client = establish_connection();
let response = client.client
.bulk(BulkParts::IndexType("user_index_v1", "user"))
.body(bodys)
.send().await?;
let successful = response.status_code().is_success();
println!("successful----->", successful);
Ok(())
所有调用 async 方法的方法 都要用 async 修饰
启动类 main.rs
mod es_client_test;
mod fusion_portrait;
mod es_client;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>>
println!("Hello, world!");
fusion_portrait::get_all_key().await;
Ok(())
Cargo.toml 文件
[package]
name = "rust-one"
version = "0.1.0"
authors = ["xxxxxxx@qq.com>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
#引用包
[dependencies]
elasticsearch = "7.7.0-alpha.1"
serde = "~1"
serde_json = "~1"
url = "2.1.1"
tokio = "0.2.20"
dgraph-tonic = "0.5.0"
threadpool = "1.8.0"
rayon = "1.3.0"
以上是关于Rust 初识及Rust的ESApi的主要内容,如果未能解决你的问题,请参考以下文章