Skip to content
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

make _formatted value user friendly :) #406

Open
wants to merge 7 commits 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
34 changes: 34 additions & 0 deletions src/Meilisearch/DefaultFormattable.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
using System.Text.Json.Serialization;

namespace Meilisearch
{
/// <summary>
/// The default implementation of <see cref="IFormatContainer{TOriginal,TFormatted}"/>
/// </summary>
/// <typeparam name="TOriginal"></typeparam>
/// <typeparam name="TFormatted"></typeparam>
public class DefaultFormattable<TOriginal, TFormatted> : IFormatContainer<TOriginal, TFormatted>
{
/// <summary>
/// Creates a formatted document
/// </summary>
/// <param name="original"></param>
/// <param name="formatted"></param>
public DefaultFormattable(TOriginal original, TFormatted formatted)
{
Original = original;
Formatted = formatted;
}

/// <summary>
/// The original document
/// </summary>
public TOriginal Original { get; }

/// <summary>
/// The formatted document
/// </summary>
[JsonPropertyName("_formatted")]
public TFormatted Formatted { get; }
}
}
23 changes: 23 additions & 0 deletions src/Meilisearch/IFormatContainer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using System.Text.Json.Serialization;

namespace Meilisearch
{
/// <summary>
/// Used to receive document formatting information
/// </summary>
/// <typeparam name="TOriginal">Original data type</typeparam>
/// <typeparam name="TFormatted">Formatted data type</typeparam>
[JsonConverter(typeof(IFormatContainerJsonConverterFactory))]
public interface IFormatContainer<TOriginal, TFormatted>
{
/// <summary>
/// The original result
/// </summary>
TOriginal Original { get; }

/// <summary>
/// The formatted result
/// </summary>
TFormatted Formatted { get; }
}
}
64 changes: 64 additions & 0 deletions src/Meilisearch/IFormatContainerJsonConverter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
using System;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace Meilisearch
{
public class IFormatContainerJsonConverterFactory : JsonConverterFactory
{
public override bool CanConvert(Type typeToConvert)
{
return typeToConvert.IsInterface
&& typeToConvert.IsGenericType
&& (typeToConvert.GetGenericTypeDefinition() == typeof(IFormatContainer<,>));
}

public override JsonConverter CreateConverter(
Type typeToConvert,
JsonSerializerOptions options
)
{
var genericArgs = typeToConvert.GetGenericArguments();
var converterType = typeof(IFormatContainerJsonConverter<,>).MakeGenericType(
genericArgs[0],
genericArgs[1]
);
var converter = (JsonConverter)Activator.CreateInstance(converterType);
return converter;
}
}

public class IFormatContainerJsonConverter<TOriginal, TFormatted>
: JsonConverter<IFormatContainer<TOriginal, TFormatted>>
where TFormatted : class
where TOriginal : class
{
public override IFormatContainer<TOriginal, TFormatted> Read(
ref Utf8JsonReader reader,
Type typeToConvert,
JsonSerializerOptions options
)
{
var document = JsonSerializer.Deserialize<JsonElement>(ref reader, options);
var original = document.Deserialize<TOriginal>(options);

if (document.TryGetProperty("_formatted", out var formattedElement))
{
var formatted = formattedElement.Deserialize<TFormatted>(options);
return new DefaultFormattable<TOriginal, TFormatted>(original, formatted);
}
return new DefaultFormattable<TOriginal, TFormatted>(original, null);
}

public override void Write(
Utf8JsonWriter writer,
IFormatContainer<TOriginal, TFormatted> value,
JsonSerializerOptions options
)
{
var serialized = JsonSerializer.SerializeToNode(value.Original, options).AsObject();
serialized["_formatted"] = JsonSerializer.SerializeToNode(value.Formatted, options);
serialized.WriteTo(writer, options);
}
}
}
61 changes: 49 additions & 12 deletions src/Meilisearch/Index.Documents.cs
Original file line number Diff line number Diff line change
Expand Up @@ -456,16 +456,8 @@ public async Task<TaskInfo> DeleteAllDocumentsAsync(CancellationToken cancellati
.ConfigureAwait(false);
}

/// <summary>
/// Search documents according to search parameters.
/// </summary>
/// <param name="query">Query Parameter with Search.</param>
/// <param name="searchAttributes">Attributes to search.</param>
/// <param name="cancellationToken">The cancellation token for this call.</param>
/// <typeparam name="T">Type parameter to return.</typeparam>
/// <returns>Returns Enumerable of items.</returns>
public async Task<ISearchable<T>> SearchAsync<T>(string query,
SearchQuery searchAttributes = default(SearchQuery), CancellationToken cancellationToken = default)
private async Task<(SearchQuery, HttpResponseMessage)> SendSearchRequest(string query,
SearchQuery searchAttributes = default, CancellationToken cancellationToken = default)
{
SearchQuery body;
if (searchAttributes == null)
Expand All @@ -483,9 +475,54 @@ public async Task<TaskInfo> DeleteAllDocumentsAsync(CancellationToken cancellati
Constants.JsonSerializerOptionsRemoveNulls, cancellationToken: cancellationToken)
.ConfigureAwait(false);

return await responseMessage.Content
.ReadFromJsonAsync<ISearchable<T>>(cancellationToken: cancellationToken)
return (body, responseMessage);
}

/// <summary>
/// Search documents according to search parameters.
/// </summary>
/// <param name="query">Query Parameter with Search.</param>
/// <param name="searchAttributes">Attributes to search.</param>
/// <param name="cancellationToken">The cancellation token for this call.</param>
/// <typeparam name="T">Type parameter to return.</typeparam>
/// <returns>Returns Enumerable of items.</returns>
public async Task<ISearchable<T>> SearchAsync<T>(string query,
SearchQuery searchAttributes = default, CancellationToken cancellationToken = default)
{

var (body, responseMessage) = await SendSearchRequest(query, searchAttributes, cancellationToken);

return body.Page != null || body.HitsPerPage != null
? await responseMessage.Content
.ReadFromJsonAsync<PaginatedSearchResult<T>>(cancellationToken: cancellationToken)
.ConfigureAwait(false)
: (ISearchable<T>)await responseMessage.Content
.ReadFromJsonAsync<SearchResult<T>>(cancellationToken: cancellationToken)
.ConfigureAwait(false);
}

/// <summary>
/// Search documents according to search parameters, Including format.
/// </summary>
/// <param name="query">Query Parameter with Search.</param>
/// <param name="searchAttributes">Attributes to search.</param>
/// <param name="cancellationToken">The cancellation token for this call.</param>
/// <typeparam name="T">Type parameter to return.</typeparam>
/// <typeparam name="TFormatted">formatted document type.</typeparam>
/// <returns>Returns Enumerable of items.</returns>
public async Task<ISearchable<IFormatContainer<T, TFormatted>>> SearchAsync<T, TFormatted>(string query,
SearchQuery searchAttributes = default, CancellationToken cancellationToken = default)
{
var (body, responseMessage) = await SendSearchRequest(query, searchAttributes, cancellationToken);

return body.Page != null || body.HitsPerPage != null
? await responseMessage.Content
.ReadFromJsonAsync<PaginatedSearchResult<IFormatContainer<T, TFormatted>>>(cancellationToken: cancellationToken)
.ConfigureAwait(false)
: (ISearchable<IFormatContainer<T, TFormatted>>)await responseMessage.Content
.ReadFromJsonAsync<SearchResult<IFormatContainer<T, TFormatted>>>(cancellationToken: cancellationToken)
.ConfigureAwait(false);
}

}
}
12 changes: 0 additions & 12 deletions tests/Meilisearch.Tests/Movie.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,16 +34,4 @@ public class MovieWithIntId

public string Genre { get; set; }
}

public class FormattedMovie
{
public string Id { get; set; }

public string Name { get; set; }

public string Genre { get; set; }

#pragma warning disable SA1300
public Movie _Formatted { get; set; }
}
}
84 changes: 56 additions & 28 deletions tests/Meilisearch.Tests/SearchTests.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;

using FluentAssertions;
Expand Down Expand Up @@ -32,6 +33,33 @@ public async Task InitializeAsync()

public Task DisposeAsync() => Task.CompletedTask;

[Fact]
public async Task TestJsonConverter()
Copy link
Contributor

Choose a reason for hiding this comment

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

Why is this method asynchronous if there is no await inside?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I guess it's just a habit of making everything async 😄

{
MovieWithIntId[] movies =
{
new MovieWithIntId { Id = 1, Name = "Batman" },
new MovieWithIntId { Id = 2, Name = "Reservoir Dogs" },
new MovieWithIntId { Id = 3, Name = "Taxi Driver" },
new MovieWithIntId { Id = 4, Name = "Interstellar" },
new MovieWithIntId { Id = 5, Name = "Titanic" },
}; ;
var formattable = movies
.Select(x => new DefaultFormattable<MovieWithIntId, Movie>(x, new Movie()
{
Id = x.Id.ToString(),
Genre = x.Genre,
Name = x.Name
}))
.Cast<IFormatContainer<MovieWithIntId, Movie>>();

var elements = formattable.Select(x => JsonSerializer.SerializeToElement(x)).ToList();
elements.Should().AllSatisfy(x => x.GetProperty("_formatted").Should().NotBeNull());

var deserialized = elements.Select(x => JsonSerializer.Deserialize<IFormatContainer<MovieWithIntId, Movie>>(x)).ToList();
deserialized.Should().AllSatisfy(x => x.Formatted.Should().NotBeNull());
}

[Fact]
public async Task BasicSearch()
{
Expand Down Expand Up @@ -107,46 +135,46 @@ public async Task CustomSearchWithAttributesToHighlight()
task.TaskUid.Should().BeGreaterOrEqualTo(0);
await _basicIndex.WaitForTaskAsync(task.TaskUid);

var movies = await _basicIndex.SearchAsync<FormattedMovie>(
var movies = await _basicIndex.SearchAsync<Movie, Movie>(
"man",
new SearchQuery { AttributesToHighlight = new string[] { "name" } });
movies.Hits.Should().NotBeEmpty();
movies.Hits.First().Id.Should().NotBeEmpty();
movies.Hits.First().Name.Should().NotBeEmpty();
movies.Hits.First().Genre.Should().NotBeEmpty();
movies.Hits.First()._Formatted.Name.Should().NotBeEmpty();
movies.Hits.First().Original.Id.Should().NotBeEmpty();
movies.Hits.First().Original.Name.Should().NotBeEmpty();
movies.Hits.First().Original.Genre.Should().NotBeEmpty();
movies.Hits.First().Formatted.Name.Should().NotBeEmpty();
}

[Fact]
public async Task CustomSearchWithNoQuery()
{
var movies = await _basicIndex.SearchAsync<FormattedMovie>(
var movies = await _basicIndex.SearchAsync<Movie, Movie>(
null,
new SearchQuery { AttributesToHighlight = new string[] { "name" } });
movies.Hits.Should().NotBeEmpty();
movies.Hits.First().Id.Should().NotBeNull();
movies.Hits.First().Name.Should().NotBeNull();
movies.Hits.First()._Formatted.Id.Should().NotBeNull();
movies.Hits.First()._Formatted.Name.Should().NotBeNull();
movies.Hits.First().Original.Id.Should().NotBeNull();
movies.Hits.First().Original.Name.Should().NotBeNull();
movies.Hits.First().Formatted.Id.Should().NotBeNull();
movies.Hits.First().Formatted.Name.Should().NotBeNull();
}

[Fact]
public async Task CustomSearchWithEmptyQuery()
{
var movies = await _basicIndex.SearchAsync<FormattedMovie>(
var movies = await _basicIndex.SearchAsync<Movie, Movie>(
string.Empty,
new SearchQuery { AttributesToHighlight = new string[] { "name" } });
movies.Hits.Should().NotBeEmpty();
movies.Hits.First().Id.Should().NotBeNull();
movies.Hits.First().Name.Should().NotBeNull();
movies.Hits.First()._Formatted.Id.Should().NotBeNull();
movies.Hits.First()._Formatted.Name.Should().NotBeNull();
movies.Hits.First().Original.Id.Should().NotBeNull();
movies.Hits.First().Original.Name.Should().NotBeNull();
movies.Hits.First().Formatted.Id.Should().NotBeNull();
movies.Hits.First().Formatted.Name.Should().NotBeNull();
}

[Fact]
public async Task CustomSearchWithMultipleOptions()
{
var movies = await _basicIndex.SearchAsync<FormattedMovie>(
var movies = await _basicIndex.SearchAsync<Movie, Movie>(
"man",
new SearchQuery
{
Expand All @@ -158,12 +186,12 @@ public async Task CustomSearchWithMultipleOptions()

Assert.NotEmpty(movies.Hits);
Assert.Single(movies.Hits);
Assert.NotEmpty(firstHit.Name);
Assert.NotEmpty(firstHit.Id);
Assert.Null(firstHit.Genre);
Assert.NotEmpty(firstHit._Formatted.Name);
Assert.Equal("15", firstHit._Formatted.Id);
Assert.Null(firstHit._Formatted.Genre);
Assert.NotEmpty(firstHit.Original.Name);
Assert.NotEmpty(firstHit.Original.Id);
Assert.Null(firstHit.Original.Genre);
Assert.NotEmpty(firstHit.Formatted.Name);
Assert.Equal("15", firstHit.Formatted.Id);
Assert.Null(firstHit.Formatted.Genre);
}

[Fact]
Expand Down Expand Up @@ -363,31 +391,31 @@ public async Task CustomSearchWithSort()
[Fact]
public async Task CustomSearchWithCroppingParameters()
{
var movies = await _basicIndex.SearchAsync<FormattedMovie>(
var movies = await _basicIndex.SearchAsync<Movie, Movie>(
"man",
new SearchQuery { CropLength = 1, AttributesToCrop = new string[] { "*" } }
);

Assert.NotEmpty(movies.Hits);
Assert.Equal("…Man", movies.Hits.First()._Formatted.Name);
Assert.Equal("…Man", movies.Hits.First().Formatted.Name);
}

[Fact]
public async Task CustomSearchWithCropMarker()
{
var movies = await _basicIndex.SearchAsync<FormattedMovie>(
var movies = await _basicIndex.SearchAsync<Movie, Movie>(
"man",
new SearchQuery { CropLength = 1, AttributesToCrop = new string[] { "*" }, CropMarker = "[…] " }
);

Assert.NotEmpty(movies.Hits);
Assert.Equal("[…] Man", movies.Hits.First()._Formatted.Name);
Assert.Equal("[…] Man", movies.Hits.First().Formatted.Name);
}

[Fact]
public async Task CustomSearchWithCustomHighlightTags()
{
var movies = await _basicIndex.SearchAsync<FormattedMovie>(
var movies = await _basicIndex.SearchAsync<Movie, Movie>(
"man",
new SearchQuery
{
Expand All @@ -398,7 +426,7 @@ public async Task CustomSearchWithCustomHighlightTags()
);

Assert.NotEmpty(movies.Hits);
Assert.Equal("Iron <mark>Man</mark>", movies.Hits.First()._Formatted.Name);
Assert.Equal("Iron <mark>Man</mark>", movies.Hits.First().Formatted.Name);
}

[Fact]
Expand Down