-
Notifications
You must be signed in to change notification settings - Fork 78
/
Copy pathmain.rs
165 lines (147 loc) · 4.92 KB
/
main.rs
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
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#[cfg(any(feature = "native-tls", feature = "rustls-tls"))]
use elasticsearch::cert::CertificateValidation;
use elasticsearch::{
auth::Credentials,
http::transport::{SingleNodeConnectionPool, TransportBuilder},
Elasticsearch, Error, SearchParts, DEFAULT_ADDRESS,
};
use serde_json::{json, Value};
use std::env;
use url::Url;
mod stack_overflow;
use stack_overflow::*;
use textwrap::fill;
static POSTS_INDEX: &str = "posts";
#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<String> = env::args().collect();
let query = if args.len() < 2 {
json!({
"query": {
"term": {
"type": "Question"
}
}
})
} else {
json!({
"query": {
"bool": {
"minimum_should_match": 1,
"should": [
{
"match": {
"title": {
"query": args[1],
"operator": "and"
}
}
},
{
"match": {
"body": {
"query": args[1],
"operator": "and"
}
}
}
],
"filter": {
"term": {
"type": "Question"
}
}
}
}
})
};
let client = create_client()?;
let mut response = client
.search(SearchParts::Index(&[POSTS_INDEX]))
.body(query)
.pretty(true)
.send()
.await?;
// turn the response into an Error if status code is unsuccessful
response = response.error_for_status_code()?;
let json: Value = response.json().await?;
let questions: Vec<Question> = json["hits"]["hits"]
.as_array()
.unwrap()
.iter()
.map(|h| serde_json::from_value(h["_source"].clone()).unwrap())
.collect();
for question in questions {
println!(
"{} - https://stackoverflow.com/q/{}",
question.title, question.id
);
println!();
println!("{}", fill(&question.body, 80));
println!("{}", "-".repeat(50));
}
Ok(())
}
fn create_client() -> Result<Elasticsearch, Error> {
fn cluster_addr() -> String {
match std::env::var("ELASTICSEARCH_URL") {
Ok(server) => server,
Err(_) => DEFAULT_ADDRESS.into(),
}
}
let mut url = Url::parse(cluster_addr().as_ref()).unwrap();
// if the url is https and specifies a username and password, remove from the url and set credentials
let credentials = if url.scheme() == "https" {
let username = if !url.username().is_empty() {
let u = url.username().to_string();
url.set_username("").unwrap();
u
} else {
std::env::var("ES_USERNAME").unwrap_or_else(|_| "elastic".into())
};
let password = match url.password() {
Some(p) => {
let pass = p.to_string();
url.set_password(None).unwrap();
pass
}
None => std::env::var("ES_PASSWORD").unwrap_or_else(|_| "changeme".into()),
};
Some(Credentials::Basic(username, password))
} else {
None
};
let conn_pool = SingleNodeConnectionPool::new(url);
let mut builder = TransportBuilder::new(conn_pool);
builder = match credentials {
Some(c) => {
builder = builder.auth(c);
#[cfg(any(feature = "native-tls", feature = "rustls-tls"))]
{
builder = builder.cert_validation(CertificateValidation::None);
}
builder
}
None => builder,
};
let transport = builder.build()?;
Ok(Elasticsearch::new(transport))
}