langchain_rust/schemas/document.rs
1use std::collections::HashMap;
2
3use serde::{Deserialize, Serialize};
4use serde_json::Value;
5
6/// The `Document` struct represents a document with content, metadata, and a score.
7/// The `page_content` field is a string that contains the content of the document.
8/// The `metadata` field is a `HashMap` where the keys represent metadata properties and the values represent property values.
9/// The `score` field represents a relevance score for the document and is a floating point number.
10///
11/// # Usage
12/// ```rust,ignore
13/// let my_doc = Document::new("This is the document content.".to_string())
14/// .with_metadata({
15/// let mut metadata = HashMap::new();
16/// metadata.insert("author".to_string(), json!("John Doe"));
17/// metadata
18/// })
19/// .with_score(0.75);
20/// ```
21#[derive(Debug, Clone, Serialize, Deserialize)]
22pub struct Document {
23 pub page_content: String,
24 pub metadata: HashMap<String, Value>,
25 pub score: f64,
26}
27
28impl Document {
29 /// Constructs a new `Document` with provided `page_content`, an empty `metadata` map and a `score` of 0.
30 pub fn new<S: Into<String>>(page_content: S) -> Self {
31 Document {
32 page_content: page_content.into(),
33 metadata: HashMap::new(),
34 score: 0.0,
35 }
36 }
37
38 /// Sets the `metadata` Map of the `Document` to the provided HashMap.
39 pub fn with_metadata(mut self, metadata: HashMap<String, Value>) -> Self {
40 self.metadata = metadata;
41 self
42 }
43
44 /// Sets the `score` of the `Document` to the provided float.
45 pub fn with_score(mut self, score: f64) -> Self {
46 self.score = score;
47 self
48 }
49}
50
51impl Default for Document {
52 /// Provides a default `Document` with an empty `page_content`, an empty `metadata` map and a `score` of 0.
53 fn default() -> Self {
54 Document {
55 page_content: "".to_string(),
56 metadata: HashMap::new(),
57 score: 0.0,
58 }
59 }
60}