Skip to content

Add support for similar docs query #674

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions src/indexes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use crate::{
errors::{Error, MeilisearchCommunicationError, MeilisearchError, MEILISEARCH_VERSION_HINT},
request::*,
search::*,
similar::*,
task_info::TaskInfo,
tasks::*,
DefaultHttpClient,
Expand Down Expand Up @@ -1622,6 +1623,50 @@ impl<Http: HttpClient> Index<Http> {
}
Ok(task)
}

/// Get similar documents in the index.
///
/// # Example
///
/// ```
/// # use serde::{Serialize, Deserialize};
/// # use meilisearch_sdk::{client::*, indexes::*, similar::*};
/// #
/// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700");
/// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey");
/// #
/// #[derive(Serialize, Deserialize, Debug)]
/// struct Movie {
/// name: String,
/// description: String,
/// }
/// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async {
/// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap();
/// let movies = client.index("execute_query");
///
/// // add some documents
/// # movies.add_or_replace(&[Movie{name:String::from("Interstellar"), description:String::from("Interstellar chronicles the adventures of a group of explorers who make use of a newly discovered wormhole to surpass the limitations on human space travel and conquer the vast distances involved in an interstellar voyage.")},Movie{name:String::from("Unknown"), description:String::from("Unknown")}], Some("name")).await.unwrap().wait_for_completion(&client, None, None).await.unwrap();
///
/// let query = SimilarQuery::new(&movies, "1", "default").build();
/// let results = query.similar_query::<Movie>(&query).await.unwrap();
Comment on lines +1650 to +1651
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix documentation example error

The example incorrectly calls similar_query on the query object instead of the movies index object.

 let query = SimilarQuery::new(&movies, "1", "default").build();
-let results = query.similar_query::<Movie>(&query).await.unwrap();
+let results = movies.similar_query::<Movie>(&query).await.unwrap();
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
/// let query = SimilarQuery::new(&movies, "1", "default").build();
/// let results = query.similar_query::<Movie>(&query).await.unwrap();
/// let query = SimilarQuery::new(&movies, "1", "default").build();
/// let results = movies.similar_query::<Movie>(&query).await.unwrap();
🤖 Prompt for AI Agents
In src/indexes.rs around lines 1650 to 1651, the documentation example
incorrectly calls similar_query on the query object instead of the movies index
object. Fix this by changing the call to similar_query to be on the movies index
object, passing the query as an argument, ensuring the example correctly
demonstrates usage.

///
/// assert!(results.hits.len() > 0);
/// # movies.delete().await.unwrap().wait_for_completion(&client, None, None).await.unwrap();
/// # });
/// ```
pub async fn similar_query<T: 'static + DeserializeOwned + Send + Sync>(
&self,
body: &SimilarQuery<'_, Http>,
) -> Result<SimilarResults<T>, Error> {
self.client
.http_client
.request::<(), &SimilarQuery<Http>, SimilarResults<T>>(
&format!("{}/indexes/{}/similar", self.client.host, self.uid),
Method::Post { body, query: () },
200,
)
.await
}
}

impl<Http: HttpClient> AsRef<str> for Index<Http> {
Expand Down
3 changes: 3 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,9 @@ mod tenant_tokens;
/// Module containing utilizes functions.
mod utils;

/// Module related to similar queries and results.
pub mod similar;

#[cfg(feature = "reqwest")]
pub mod reqwest;

Expand Down
2 changes: 1 addition & 1 deletion src/search.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ pub struct SearchResults<T> {
pub index_uid: Option<String>,
}

fn serialize_with_wildcard<S: Serializer, T: Serialize>(
pub(crate) fn serialize_with_wildcard<S: Serializer, T: Serialize>(
data: &Option<Selectors<T>>,
s: S,
) -> Result<S::Ok, S::Error> {
Expand Down
Loading