1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
use anyhow::{anyhow, Result};
use serde::{Deserialize, Serialize};
use serde_json::json;

pub struct Client {
    pub url: String,
}

impl Client {
    pub fn new(url: &str) -> Self {
        Client {
            url: url.to_string(),
        }
    }
    pub async fn bulk(&self, bulk_requests: &str) -> Result<BulkResponse> {
        let client = reqwest::Client::new();
        let res = client
            .post(&format!("{}/_bulk", &self.url))
            .header("Content-type", "application/x-ndjson")
            .body(bulk_requests.to_string())
            .send()
            .await?;
        let status = res.status();
        if reqwest::StatusCode::INTERNAL_SERVER_ERROR == status {
            return Err(anyhow!("internal server error {}", res.text().await?,));
        }
        let text = res.text().await?;
        let bulk_response: BulkResponse = serde_json::from_str(&text)?;
        Ok(bulk_response)
    }
}

#[derive(Serialize, Deserialize, Debug)]
pub struct BulkResponse {
    took: i64,
    errors: bool,
    pub items: Vec<BulkResponseItem>,
}

#[derive(Serialize, Deserialize, Debug)]
pub enum BulkResponseItem {
    #[allow(non_camel_case_types)]
    index(IndexResponseItem),
    #[allow(non_camel_case_types)]
    delete(DeleteResponseItem),
}

#[derive(Serialize, Deserialize, Debug)]
pub struct IndexResponseItem {
    _index: String,
    _type: String,
    _id: String,
    _version: Option<i64>,
    result: Option<String>,
    created: Option<bool>,
    pub status: i64,
    pub error: Option<BulkItemError>,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct BulkItemError {
    pub r#type: String,
    pub reason: String,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct DeleteResponseItem {
    _index: String,
    _type: String,
    _id: String,
    error: Option<BulkItemError>,
}

pub enum BulkItem {
    Index(IndexBulkItem),
    Delete(DeleteBulkItem),
}

#[derive(Debug)]
pub struct IndexBulkItem {
    pub id: String,
    pub r#type: String,
    pub parent: Option<String>,
    pub body: String,
    pub version: i64,
}

impl IndexBulkItem {
    fn to_request(&self, index: &str) -> String {
        let head = json!({
            "index": {
                "_index": index,
                "_id": &self.id,
                "_type": &self.r#type,
                "_parent": &self.parent,
                "_version_type": "external",
                "_version": &self.version,
            }
        });
        let mut body = head.to_string();
        body = body + "\n";
        body += &self.body;
        body += "\n";
        body
    }
}

#[derive(Debug)]
pub struct DeleteBulkItem {
    pub id: String,
    pub r#type: String,
    pub parent: Option<String>,
}

impl DeleteBulkItem {
    fn to_request(&self, index: &str) -> String {
        let head = json!({
            "delete": {
                "_index": index,
                "_id": &self.id,
                "_type": &self.r#type,
                "_parent": &self.parent,
            }
        });
        let mut body = head.to_string();
        body = body + "\n";
        body
    }
}

#[derive(Debug)]
pub enum Bulkable {
    Delete(DeleteBulkItem),
    Index(IndexBulkItem),
}

pub struct BulkRequestGenerator {
    pub index: String,
    pub items: Vec<Bulkable>,
}

impl BulkRequestGenerator {
    pub fn new(index: &str) -> Self {
        Self {
            index: index.to_string(),
            items: vec![],
        }
    }
    pub fn add_item(&mut self, item: Bulkable) -> &mut Self {
        &self.items.push(item);
        self
    }
    pub fn generate(&self) -> String {
        let mut body = String::new();
        for item in &self.items {
            match item {
                Bulkable::Delete(i) => {
                    body += i.to_request(&self.index).as_str();
                }
                Bulkable::Index(i) => {
                    body += i.to_request(&self.index).as_str();
                }
            }
        }
        body
    }
}