armature-framework 0.2.2

A modern, type-safe HTTP framework for Rust inspired by Angular and NestJS. Features dependency injection, decorators, middleware, authentication (JWT/OAuth2/SAML), validation, OpenAPI/Swagger, caching, job queues, and observability.
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
# OpenSearch Guide

Integration guide for OpenSearch with the Armature framework.

## Table of Contents

- [Overview]#overview
- [Features]#features
- [Installation]#installation
- [Quick Start]#quick-start
- [Configuration]#configuration
- [Document Operations]#document-operations
- [Search]#search
- [Query DSL]#query-dsl
- [Aggregations]#aggregations
- [Index Management]#index-management
- [Bulk Operations]#bulk-operations
- [AWS OpenSearch Service]#aws-opensearch-service
- [Best Practices]#best-practices
- [Examples]#examples

---

## Overview

`armature-opensearch` provides a high-level client for OpenSearch with full support for:

- Document indexing, searching, and management
- Query DSL builder for complex queries
- Aggregations for analytics
- Index lifecycle management
- Bulk operations for high throughput
- AWS OpenSearch Service authentication

---

## Features

- ✅ Type-safe document operations with the `Document` trait
- ✅ Fluent query DSL builder
- ✅ Search with pagination, sorting, highlighting
- ✅ Aggregations (terms, histogram, metrics)
- ✅ Index management (create, delete, mappings)
- ✅ Bulk operations (index, delete)
- ✅ AWS OpenSearch Service support
- ✅ TLS support (rustls/native-tls)

---

## Installation

Add to your `Cargo.toml`:

```toml
[dependencies]
armature-opensearch = "0.1"
```

### Feature Flags

| Feature | Default | Description |
|---------|---------|-------------|
| `rustls` || TLS via rustls |
| `native-tls` | | TLS via native-tls |
| `aws-auth` | | AWS OpenSearch Service authentication |
| `bulk-stream` | | Streaming bulk operations |

```toml
# With AWS auth
armature-opensearch = { version = "0.1", features = ["aws-auth"] }

# With native TLS
armature-opensearch = { version = "0.1", default-features = false, features = ["native-tls"] }
```

---

## Quick Start

### Define a Document

```rust
use armature_opensearch::{Document, OpenSearchClient, OpenSearchConfig};
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
struct Article {
    title: String,
    body: String,
    author: String,
    tags: Vec<String>,
    published_at: String,
}

impl Document for Article {
    fn index_name() -> &'static str {
        "articles"
    }
}
```

### Create a Client

```rust
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = OpenSearchClient::new(
        OpenSearchConfig::new("http://localhost:9200")
    )?;

    // Index a document
    let article = Article {
        title: "Getting Started with OpenSearch".to_string(),
        body: "OpenSearch is a powerful search engine...".to_string(),
        author: "Alice".to_string(),
        tags: vec!["tutorial".to_string(), "search".to_string()],
        published_at: "2024-12-20".to_string(),
    };

    client.index("article-1", &article).await?;

    // Search
    let results: Vec<Article> = client
        .search()
        .query_string("getting started")
        .size(10)
        .execute()
        .await?;

    println!("Found {} articles", results.len());
    Ok(())
}
```

---

## Configuration

### Basic Configuration

```rust
use armature_opensearch::OpenSearchConfig;

let config = OpenSearchConfig::new("http://localhost:9200");
```

### With Authentication

```rust
let config = OpenSearchConfig::new("https://opensearch.example.com")
    .with_basic_auth("admin", "password");
```

### With TLS

```rust
use armature_opensearch::TlsConfig;

let config = OpenSearchConfig::new("https://opensearch.example.com")
    .with_tls(TlsConfig::with_ca_cert("/path/to/ca.crt"));
```

### Cluster Configuration

```rust
let config = OpenSearchConfig::cluster(vec![
    "http://node1:9200".to_string(),
    "http://node2:9200".to_string(),
    "http://node3:9200".to_string(),
]);
```

### Configuration Options

```rust
let config = OpenSearchConfig::new("http://localhost:9200")
    .with_basic_auth("user", "pass")
    .with_connect_timeout(Duration::from_secs(10))
    .with_request_timeout(Duration::from_secs(30))
    .with_compression(true)
    .with_max_retries(3);
```

---

## Document Operations

### Index a Document

```rust
// With explicit ID
client.index("doc-1", &article).await?;

// With auto-generated ID
let id = client.index_auto_id(&article).await?;
```

### Get a Document

```rust
let article: Option<Article> = client.get("doc-1").await?;

if let Some(article) = article {
    println!("Found: {}", article.title);
}
```

### Check if Document Exists

```rust
let exists = client.exists::<Article>("doc-1").await?;
```

### Update a Document

```rust
// Full update
article.title = "Updated Title".to_string();
client.update("doc-1", &article).await?;

// Partial update
use serde_json::json;
client.partial_update::<Article>("doc-1", json!({
    "title": "New Title"
})).await?;
```

### Delete a Document

```rust
let deleted = client.delete::<Article>("doc-1").await?;
```

### Delete by Query

```rust
use serde_json::json;

let deleted_count = client.delete_by_query(
    "articles",
    json!({ "term": { "author": "Alice" } })
).await?;
```

---

## Search

### Basic Search

```rust
let results: Vec<Article> = client
    .search()
    .index("articles")
    .query_string("opensearch tutorial")
    .execute()
    .await?;
```

### With Pagination

```rust
let results: Vec<Article> = client
    .search()
    .index("articles")
    .from(0)
    .size(20)
    .execute()
    .await?;
```

### With Sorting

```rust
use armature_opensearch::SortOrder;

let results: Vec<Article> = client
    .search()
    .index("articles")
    .sort_by("published_at", SortOrder::Desc)
    .sort_by_score(SortOrder::Desc)
    .execute()
    .await?;
```

### With Source Filtering

```rust
let results: Vec<Article> = client
    .search()
    .index("articles")
    .source_includes(vec!["title".to_string(), "author".to_string()])
    .source_excludes(vec!["body".to_string()])
    .execute()
    .await?;
```

### With Highlighting

```rust
let results = client
    .search()
    .index("articles")
    .query_string("opensearch")
    .highlight(vec!["title".to_string(), "body".to_string()])
    .execute_with_meta::<Article>()
    .await?;

for hit in results.hits {
    if let Some(highlight) = &hit.meta.highlight {
        if let Some(titles) = highlight.get("title") {
            println!("Highlighted title: {:?}", titles);
        }
    }
}
```

### Search Result with Metadata

```rust
let result = client
    .search()
    .index("articles")
    .query_string("tutorial")
    .execute_with_meta::<Article>()
    .await?;

println!("Total hits: {}", result.total);
println!("Max score: {:?}", result.max_score);
println!("Took: {}ms", result.took_ms);

for hit in result.hits {
    println!("ID: {}, Score: {:?}", hit.meta.id, hit.meta.score);
    println!("Title: {}", hit.doc.title);
}
```

### Count Documents

```rust
let count = client
    .search()
    .index("articles")
    .query_string("tutorial")
    .count()
    .await?;
```

---

## Query DSL

### Match Query

```rust
use armature_opensearch::{Query, MatchQuery};

let results: Vec<Article> = client
    .search()
    .query(Query::Match(MatchQuery::new("title", "opensearch tutorial")))
    .execute()
    .await?;
```

### Term Query (Exact Match)

```rust
use armature_opensearch::{Query, TermQuery};

let results: Vec<Article> = client
    .search()
    .query(Query::Term(TermQuery::new("author", "Alice")))
    .execute()
    .await?;
```

### Range Query

```rust
use armature_opensearch::{Query, RangeQuery};
use serde_json::json;

let results: Vec<Article> = client
    .search()
    .query(Query::Range(
        RangeQuery::new("published_at")
            .gte(json!("2024-01-01"))
            .lte(json!("2024-12-31"))
    ))
    .execute()
    .await?;
```

### Bool Query (Compound)

```rust
use armature_opensearch::{Query, MatchQuery, TermQuery, BoolQueryBuilder};

let query = BoolQueryBuilder::new()
    .must(Query::Match(MatchQuery::new("title", "opensearch")))
    .must(Query::Term(TermQuery::new("author", "Alice")))
    .should(Query::Match(MatchQuery::new("tags", "tutorial")))
    .must_not(Query::Term(TermQuery::new("status", "draft")))
    .filter(Query::Range(RangeQuery::new("published_at").gte(json!("2024-01-01"))))
    .minimum_should_match(1)
    .build();

let results: Vec<Article> = client
    .search()
    .query(query)
    .execute()
    .await?;
```

### Query String Query

```rust
// Supports Lucene query syntax
let results: Vec<Article> = client
    .search()
    .query_string("title:opensearch AND author:Alice")
    .execute()
    .await?;
```

### Raw JSON Query

```rust
use serde_json::json;

let results: Vec<Article> = client
    .search()
    .query_json(json!({
        "bool": {
            "must": [
                { "match": { "title": "opensearch" } }
            ],
            "filter": [
                { "term": { "status": "published" } }
            ]
        }
    }))
    .execute()
    .await?;
```

---

## Aggregations

### Terms Aggregation

```rust
use armature_opensearch::Aggregation;

let result = client
    .search()
    .index("articles")
    .aggregation("by_author", Aggregation::terms("author"))
    .size(0)  // Only return aggregations
    .execute_with_meta::<Article>()
    .await?;

if let Some(aggs) = result.aggregations {
    println!("Aggregations: {:?}", aggs);
}
```

### Metrics Aggregations

```rust
let result = client
    .search()
    .index("articles")
    .aggregation("avg_views", Aggregation::avg("view_count"))
    .aggregation("max_views", Aggregation::Max { field: "view_count".to_string() })
    .aggregation("total_views", Aggregation::Sum { field: "view_count".to_string() })
    .execute_with_meta::<Article>()
    .await?;
```

### Date Histogram

```rust
let result = client
    .search()
    .index("articles")
    .aggregation("articles_over_time", Aggregation::DateHistogram {
        field: "published_at".to_string(),
        calendar_interval: Some("month".to_string()),
        fixed_interval: None,
    })
    .execute_with_meta::<Article>()
    .await?;
```

---

## Index Management

### Create an Index

```rust
use armature_opensearch::{IndexSettings, Mapping, MappingField};

let settings = IndexSettings::new()
    .shards(3)
    .replicas(1)
    .refresh_interval("1s")
    .mappings(
        Mapping::new()
            .field("title", MappingField::text().analyzer("standard"))
            .field("author", MappingField::keyword())
            .field("published_at", MappingField::date())
            .field("view_count", MappingField::integer())
    );

client.indices().create("articles", settings).await?;
```

### Check if Index Exists

```rust
let exists = client.indices().exists("articles").await?;
```

### Delete an Index

```rust
client.indices().delete("articles").await?;
```

### Update Mappings

```rust
let mapping = Mapping::new()
    .field("new_field", MappingField::keyword());

client.indices().put_mapping("articles", mapping).await?;
```

### Index Aliases

```rust
// Create alias
client.indices().create_alias("articles", "articles-read").await?;

// Delete alias
client.indices().delete_alias("articles", "articles-read").await?;
```

### List Indices

```rust
let indices = client.indices().list().await?;

for index in indices {
    println!("{}: {} docs, {}", index.name, index.docs_count, index.store_size);
}
```

### Refresh Index

```rust
// Make recent changes searchable
client.refresh("articles").await?;
```

---

## Bulk Operations

### Bulk Index

```rust
let docs = vec![
    ("doc-1".to_string(), article1),
    ("doc-2".to_string(), article2),
    ("doc-3".to_string(), article3),
];

let indexed_count = client.bulk_index(docs).await?;
```

### Bulk Delete

```rust
let ids = vec![
    "doc-1".to_string(),
    "doc-2".to_string(),
    "doc-3".to_string(),
];

let deleted_count = client.bulk_delete::<Article>(ids).await?;
```

---

## AWS OpenSearch Service

Enable the `aws-auth` feature:

```toml
armature-opensearch = { version = "0.1", features = ["aws-auth"] }
```

### Configuration

```rust
let config = OpenSearchConfig::new("https://search-mydomain-xxxx.us-east-1.es.amazonaws.com")
    .with_aws_region("us-east-1");

let client = OpenSearchClient::new(config)?;
```

AWS credentials are automatically loaded from the environment (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) or IAM role.

---

## Best Practices

### 1. Use Appropriate Analyzers

```rust
// Full-text search fields
MappingField::text().analyzer("standard")

// Exact match fields (IDs, enums, tags)
MappingField::keyword()
```

### 2. Use Filters for Non-Scoring Queries

```rust
// ✅ Good - uses filter for exact match (faster, cached)
BoolQueryBuilder::new()
    .must(Query::Match(MatchQuery::new("title", "search")))
    .filter(Query::Term(TermQuery::new("status", "published")))
    .build()

// ❌ Less efficient - scoring on exact match
BoolQueryBuilder::new()
    .must(Query::Match(MatchQuery::new("title", "search")))
    .must(Query::Term(TermQuery::new("status", "published")))
    .build()
```

### 3. Use Bulk Operations for High Throughput

```rust
// ✅ Good - single bulk request
client.bulk_index(docs).await?;

// ❌ Slow - individual requests
for (id, doc) in docs {
    client.index(&id, &doc).await?;
}
```

### 4. Refresh After Bulk Operations

```rust
client.bulk_index(docs).await?;
client.refresh("articles").await?;  // Make searchable immediately
```

### 5. Use Pagination for Large Result Sets

```rust
let mut from = 0;
let size = 100;

loop {
    let results: Vec<Article> = client
        .search()
        .from(from)
        .size(size)
        .execute()
        .await?;

    if results.is_empty() {
        break;
    }

    // Process results
    from += size;
}
```

---

## Examples

### Full-Text Search with Filters

```rust
let results: Vec<Article> = client
    .search()
    .index("articles")
    .query(
        BoolQueryBuilder::new()
            .must(Query::Match(MatchQuery::new("body", "rust programming")))
            .filter(Query::Term(TermQuery::new("published", true)))
            .filter(Query::Range(RangeQuery::new("published_at").gte(json!("2024-01-01"))))
            .build()
    )
    .sort_by("_score", SortOrder::Desc)
    .sort_by("published_at", SortOrder::Desc)
    .highlight(vec!["title".to_string(), "body".to_string()])
    .size(20)
    .execute()
    .await?;
```

### Analytics Dashboard

```rust
let result = client
    .search()
    .index("articles")
    .aggregation("by_author", Aggregation::terms("author"))
    .aggregation("by_month", Aggregation::DateHistogram {
        field: "published_at".to_string(),
        calendar_interval: Some("month".to_string()),
        fixed_interval: None,
    })
    .aggregation("avg_views", Aggregation::avg("view_count"))
    .aggregation("total_articles", Aggregation::Cardinality { field: "_id".to_string() })
    .size(0)
    .execute_with_meta::<Article>()
    .await?;
```

### Health Check

```rust
if client.ping().await? {
    let health = client.health().await?;
    println!("Cluster status: {}", health["status"]);
}
```

---

## Summary

### Key APIs

```rust
// Client
OpenSearchClient::new(config)?

// Documents
client.index(id, &doc).await?
client.get::<T>(id).await?
client.update(id, &doc).await?
client.delete::<T>(id).await?

// Search
client.search().query(...).execute::<T>().await?

// Index Management
client.indices().create(name, settings).await?
client.indices().delete(name).await?

// Bulk
client.bulk_index(docs).await?
client.bulk_delete::<T>(ids).await?
```

### Environment Variables

For AWS OpenSearch Service:
```bash
AWS_ACCESS_KEY_ID=xxx
AWS_SECRET_ACCESS_KEY=xxx
AWS_REGION=us-east-1
```

---

**Happy searching!** 🔍