aboutsummaryrefslogtreecommitdiffstats
path: root/fatcat-cli/src/search.rs
blob: 7d03f6fee450e46139db1758f673879767665105 (plain)
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
use crate::SearchEntityType;
use anyhow::{anyhow, Result};
use log::{self, info};
use serde_json::json;
use std::time::Duration;

pub struct SearchResults {
    pub entity_type: SearchEntityType,
    pub limit: Option<u64>,
    pub count: u64,
    pub took_ms: u64,
    offset: u64,
    batch: Vec<serde_json::Value>,
    scroll_id: Option<String>,
    scroll_url: String,
    http_client: reqwest::blocking::Client,
}

impl Iterator for SearchResults {
    type Item = Result<serde_json::Value>;

    fn next(&mut self) -> Option<Result<serde_json::Value>> {
        // if we already hit limit, bail early
        if let Some(l) = self.limit {
            if self.offset >= l {
                return None;
            }
        }
        // if current batch is empty, and we are scrolling, refill the current batch
        if self.batch.is_empty() && self.scroll_id.is_some() {
            let response = self
                .http_client
                .get(&self.scroll_url)
                .header("Content-Type", "application/json")
                .body(
                    json!({
                        "scroll": "2m",
                        "scroll_id": self.scroll_id.clone().unwrap(),
                    })
                    .to_string(),
                )
                .send();
            let response = match response {
                Err(e) => return Some(Err(e.into())),
                Ok(v) => v,
            };
            if !response.status().is_success() {
                return Some(Err(anyhow!("search error, status={}", response.status())));
            };
            let body: serde_json::Value = match response.json() {
                Err(e) => return Some(Err(e.into())),
                Ok(v) => v,
            };
            self.scroll_id = Some(body["_scroll_id"].as_str().unwrap().to_string());
            self.batch = body["hits"]["hits"].as_array().unwrap().to_vec();
        }

        // return next hit from the most recent batch
        if !self.batch.is_empty() {
            self.offset += 1;
            let val = self.batch.pop().unwrap();
            let source = val["_source"].clone();
            return Some(Ok(source));
        }

        // if batch is empty and couldn't be refilled, terminate
        // TODO: should we raise error if ended early?
        None
    }
}

pub fn crude_search(
    api_host: &str,
    entity_type: SearchEntityType,
    limit: Option<u64>,
    terms: Vec<String>,
) -> Result<SearchResults> {
    let index = match entity_type {
        SearchEntityType::Release => "fatcat_release",
        SearchEntityType::Container => "fatcat_container",
        SearchEntityType::File => "fatcat_file",
        SearchEntityType::Scholar => "scholar_fulltext",
    };
    let http_client = reqwest::blocking::Client::builder()
        .timeout(Duration::from_secs(10))
        .danger_accept_invalid_certs(true)
        .build()
        .expect("ERROR :: Could not build reqwest client");

    let query: String = if terms.is_empty() {
        "*".to_string()
    } else {
        terms.join(" ")
    };
    info!("Search query string: {}", query);
    let request_url = format!("{}/{}/_search", api_host, index);
    let scroll_url = format!("{}/_search/scroll", api_host);

    // sort by _doc for (potentially) very large result sets
    let (scroll_mode, sort_mode, size) = match limit {
        None => (true, "_doc", 100),
        Some(l) if l > 100 => (true, "_doc", 100),
        Some(l) => (false, "_score", l),
    };

    let query_body = match entity_type {
        SearchEntityType::Release => json!({
            "query": {
                "boosting": {
                    "positive": {
                        "bool": {
                            "must": {
                                "query_string": {
                                    "query": query,
                                    "default_operator": "AND",
                                    "analyze_wildcard": true,
                                    "allow_leading_wildcard": false,
                                    "lenient": true,
                                    "fields": [
                                        "title^2",
                                        "biblio",
                                    ],
                                },
                            },
                            "should": {
                                "term": { "in_ia": true },
                            },
                        },
                    },
                    "negative": {
                        "bool": {
                            "should": [
                                {"bool": { "must_not" : { "exists": { "field": "title" }}}},
                                {"bool": { "must_not" : { "exists": { "field": "year" }}}},
                                {"bool": { "must_not" : { "exists": { "field": "type" }}}},
                                {"bool": { "must_not" : { "exists": { "field": "stage" }}}},
                            ],
                        },
                    },
                    "negative_boost": 0.5,
                },
            },
            "size": size,
            "sort": [ sort_mode ],
            "track_total_hits": true,
        }),
        SearchEntityType::Container => json!({
            "query": {
                "query_string": {
                    "query": query,
                    "default_operator": "AND",
                    "analyze_wildcard": true,
                    "allow_leading_wildcard": false,
                    "lenient": true,
                    "fields": [
                        "name^2",
                        "biblio",
                    ],
                },
            },
            "size": size,
            "sort": [ sort_mode ],
            "track_total_hits": true,
        }),
        SearchEntityType::File => json!({
            "query": {
                "query_string": {
                    "query": query,
                    "default_operator": "AND",
                    "analyze_wildcard": true,
                    "allow_leading_wildcard": false,
                    "lenient": true,
                },
            },
            "size": size,
            "sort": [ sort_mode ],
            "track_total_hits": true,
        }),
        SearchEntityType::Scholar => json!({
            "query": {
                "boosting": {
                    "positive": {
                        "bool": {
                            "must": {
                                "query_string": {
                                    "query": query,
                                    "default_operator": "AND",
                                    "analyze_wildcard": true,
                                    "allow_leading_wildcard": false,
                                    "lenient": true,
                                    "quote_field_suffix": ".exact",
                                    "fields": [
                                        "title^4",
                                        "biblio_all^3",
                                        "everything",
                                    ],
                                },
                            },
                            "should": {
                                "terms": { "access_type": ["ia_sim", "ia_file", "wayback"]},
                            },
                        },
                    },
                    "negative": {
                        "bool": {
                            "should": [
                                {"bool": { "must_not" : { "exists": { "field": "year" }}}},
                                {"bool": { "must_not" : { "exists": { "field": "type" }}}},
                                {"bool": { "must_not" : { "exists": { "field": "stage" }}}},
                                {"bool": { "must_not" : { "exists": { "field": "biblio.container_name" }}}},
                            ],
                        },
                    },
                    "negative_boost": 0.5,
                },
            },
            "size": size,
            "sort": [ sort_mode ],
            "track_total_hits": true,
        }),
    }.to_string();

    let mut request = http_client
        .get(&request_url)
        .header("Content-Type", "application/json")
        .body(query_body);

    if scroll_mode {
        request = request.query(&[("scroll", "2m")]);
    }

    let response = request.send()?;

    if !response.status().is_success() {
        return Err(anyhow!("search error, status={}", response.status()));
    }
    //println!("{:?}", response);
    let body: serde_json::Value = response.json()?;

    let scroll_id = if scroll_mode {
        Some(body["_scroll_id"].as_str().unwrap().to_string())
    } else {
        None
    };

    Ok(SearchResults {
        entity_type,
        limit,
        count: body["hits"]["total"]["value"].as_u64().unwrap(),
        took_ms: body["took"].as_u64().unwrap(),
        offset: 0,
        batch: body["hits"]["hits"].as_array().unwrap().to_vec(),
        scroll_id,
        scroll_url,
        http_client,
    })
}