More advanced features of the high-level .NET client (OpenSearch.Client)

The following example illustrates more advanced features of OpenSearch.Client. For a simple example, see the Getting started guide. This example uses the following Student class.

  1. public class Student
  2. {
  3. public int Id { get; init; }
  4. public string FirstName { get; init; }
  5. public string LastName { get; init; }
  6. public int GradYear { get; init; }
  7. public double Gpa { get; init; }
  8. }

copy

Mappings

OpenSearch uses dynamic mapping to infer field types of the documents that are indexed. However, to have more control over the schema of your document, you can pass an explicit mapping to OpenSearch. You can define data types for some or all fields of your document in this mapping.

Similarly, OpenSearch.Client uses auto mapping to infer field data types based on the types of the class’s properties. To use auto mapping, create a students index using the AutoMap’s default constructor:

  1. var createResponse = await osClient.Indices.CreateAsync("students",
  2. c => c.Map(m => m.AutoMap<Student>()));

copy

If you use auto mapping, Id and GradYear are mapped as integers, Gpa is mapped as a double, and FirstName and LastName are mapped as text with a keyword subfield. If you want to search for FirstName and LastName and allow only case-sensitive full matches, you can suppress analyzing by mapping these fields as keyword only. In Query DSL, you can accomplish this using the following query:

  1. PUT students
  2. {
  3. "mappings" : {
  4. "properties" : {
  5. "firstName" : {
  6. "type" : "keyword"
  7. },
  8. "lastName" : {
  9. "type" : "keyword"
  10. }
  11. }
  12. }
  13. }

In OpenSearch.Client, you can use fluid lambda syntax to mark these fields as keywords:

  1. var createResponse = await osClient.Indices.CreateAsync(index,
  2. c => c.Map(m => m.AutoMap<Student>()
  3. .Properties<Student>(p => p
  4. .Keyword(k => k.Name(f => f.FirstName))
  5. .Keyword(k => k.Name(f => f.LastName)))));

copy

Settings

In addition to mappings, you can specify settings like the number of primary and replica shards when creating an index. The following query sets the number of primary shards to 1 and the number of replica shards to 2:

  1. PUT students
  2. {
  3. "mappings" : {
  4. "properties" : {
  5. "firstName" : {
  6. "type" : "keyword"
  7. },
  8. "lastName" : {
  9. "type" : "keyword"
  10. }
  11. }
  12. },
  13. "settings": {
  14. "number_of_shards": 1,
  15. "number_of_replicas": 2
  16. }
  17. }

In OpenSearch.Client, the equivalent of the above query is the following:

  1. var createResponse = await osClient.Indices.CreateAsync(index,
  2. c => c.Map(m => m.AutoMap<Student>()
  3. .Properties<Student>(p => p
  4. .Keyword(k => k.Name(f => f.FirstName))
  5. .Keyword(k => k.Name(f => f.LastName))))
  6. .Settings(s => s.NumberOfShards(1).NumberOfReplicas(2)));

copy

Indexing multiple documents using the Bulk API

In addition to indexing one document using Index and IndexDocument and indexing multiple documents using IndexMany, you can gain more control over document indexing by using Bulk or BulkAll. Indexing documents individually is inefficient because it creates an HTTP request for every document sent. The BulkAll helper frees you from handling retry, chunking or back off request functionality. It automatically retries if the request fails, backs off if the server is down, and controls how many documents are sent in one HTTP request.

In the following example, BulkAll is configured with the index name, number of back off retries, and back off time. Additionally, the maximum degrees of parallelism setting controls the number of parallel HTTP requests containing the data. Finally, the size parameter signals how many documents are sent in one HTTP request.

We recommend setting the size to 100–1000 documents in production.

BulkAll takes a stream of data and returns an Observable that you can use to observe the background operation.

  1. var bulkAll = osClient.BulkAll(ReadData(), r => r
  2. .Index(index)
  3. .BackOffRetries(2)
  4. .BackOffTime("30s")
  5. .MaxDegreeOfParallelism(4)
  6. .Size(100));

copy

Searching with Boolean query

OpenSearch.Client exposes full OpenSearch query capability. In addition to simple searches that use the match query, you can create a more complex Boolean query to search for students who graduated in 2022 and sort them by last name. In the example below, search is limited to 10 documents, and the scroll API is used to control the pagination of results.

  1. var gradResponse = await osClient.SearchAsync<Student>(s => s
  2. .Index(index)
  3. .From(0)
  4. .Size(10)
  5. .Scroll("1m")
  6. .Query(q => q
  7. .Bool(b => b
  8. .Filter(f => f
  9. .Term(t => t.Field(fld => fld.GradYear).Value(2022)))))
  10. .Sort(srt => srt.Ascending(f => f.LastName)));

copy

The response contains the Documents property with matching documents from OpenSearch. The data is in the form of deserialized JSON objects of Student type, so you can access their properties in a strongly typed fashion. All serialization and deserialization is handled by OpenSearch.Client.

Aggregations

OpenSearch.Client includes the full OpenSearch query functionality, including aggregations. In addition to grouping search results into buckets (for example, grouping students by GPA ranges), you can calculate metrics like sum or average. The following query calculates the average GPA of all students in the index.

Setting Size to 0 means OpenSearch will only return the aggregation, not the actual documents.

  1. var aggResponse = await osClient.SearchAsync<Student>(s => s
  2. .Index(index)
  3. .Size(0)
  4. .Aggregations(a => a
  5. .Average("average gpa",
  6. avg => avg.Field(fld => fld.Gpa))));

copy

Sample program for creating an index and indexing data

The following program creates an index, reads a stream of student records from a comma-separated file and indexes this data into OpenSearch.

  1. using OpenSearch.Client;
  2. namespace NetClientProgram;
  3. internal class Program
  4. {
  5. private const string index = "students";
  6. public static IOpenSearchClient osClient = new OpenSearchClient();
  7. public static async Task Main(string[] args)
  8. {
  9. // Check if the index with the name "students" exists
  10. var existResponse = await osClient.Indices.ExistsAsync(index);
  11. if (!existResponse.Exists) // There is no index with this name
  12. {
  13. // Create an index "students"
  14. // Map FirstName and LastName as keyword
  15. var createResponse = await osClient.Indices.CreateAsync(index,
  16. c => c.Map(m => m.AutoMap<Student>()
  17. .Properties<Student>(p => p
  18. .Keyword(k => k.Name(f => f.FirstName))
  19. .Keyword(k => k.Name(f => f.LastName))))
  20. .Settings(s => s.NumberOfShards(1).NumberOfReplicas(1)));
  21. if (!createResponse.IsValid && !createResponse.Acknowledged)
  22. {
  23. throw new Exception("Create response is invalid.");
  24. }
  25. // Take a stream of data and send it to OpenSearch
  26. var bulkAll = osClient.BulkAll(ReadData(), r => r
  27. .Index(index)
  28. .BackOffRetries(2)
  29. .BackOffTime("20s")
  30. .MaxDegreeOfParallelism(4)
  31. .Size(10));
  32. // Wait until the data upload is complete.
  33. // FromMinutes specifies a timeout.
  34. // r is a response object that is returned as the data is indexed.
  35. bulkAll.Wait(TimeSpan.FromMinutes(10), r =>
  36. Console.WriteLine("Data chunk indexed"));
  37. }
  38. }
  39. // Reads student data in the form "Id,FirsName,LastName,GradYear,Gpa"
  40. public static IEnumerable<Student> ReadData()
  41. {
  42. var file = new StreamReader("C:\\search\\students.csv");
  43. string s;
  44. while ((s = file.ReadLine()) is not null)
  45. {
  46. yield return new Student(s);
  47. }
  48. }
  49. }

copy

The following program searches students by name and graduation date and calculates the average GPA.

  1. using OpenSearch.Client;
  2. namespace NetClientProgram;
  3. internal class Program
  4. {
  5. private const string index = "students";
  6. public static IOpenSearchClient osClient = new OpenSearchClient();
  7. public static async Task Main(string[] args)
  8. {
  9. await SearchByName();
  10. await SearchByGradDate();
  11. await CalculateAverageGpa();
  12. }
  13. private static async Task SearchByName()
  14. {
  15. Console.WriteLine("Searching for name......");
  16. var nameResponse = await osClient.SearchAsync<Student>(s => s
  17. .Index(index)
  18. .Query(q => q
  19. .Match(m => m
  20. .Field(fld => fld.FirstName)
  21. .Query("Zhang"))));
  22. if (!nameResponse.IsValid)
  23. {
  24. throw new Exception("Aggregation query response is not valid.");
  25. }
  26. foreach (var s in nameResponse.Documents)
  27. {
  28. Console.WriteLine($"{s.Id} {s.LastName} " +
  29. $"{s.FirstName} {s.Gpa} {s.GradYear}");
  30. }
  31. }
  32. private static async Task SearchByGradDate()
  33. {
  34. Console.WriteLine("Searching for grad date......");
  35. // Search for all students who graduated in 2022
  36. var gradResponse = await osClient.SearchAsync<Student>(s => s
  37. .Index(index)
  38. .From(0)
  39. .Size(2)
  40. .Scroll("1m")
  41. .Query(q => q
  42. .Bool(b => b
  43. .Filter(f => f
  44. .Term(t => t.Field(fld => fld.GradYear).Value(2022)))))
  45. .Sort(srt => srt.Ascending(f => f.LastName))
  46. .Size(10));
  47. if (!gradResponse.IsValid)
  48. {
  49. throw new Exception("Grad date query response is not valid.");
  50. }
  51. while (gradResponse.Documents.Any())
  52. {
  53. foreach (var data in gradResponse.Documents)
  54. {
  55. Console.WriteLine($"{data.Id} {data.LastName} {data.FirstName} " +
  56. $"{data.Gpa} {data.GradYear}");
  57. }
  58. gradResponse = osClient.Scroll<Student>("1m", gradResponse.ScrollId);
  59. }
  60. }
  61. public static async Task CalculateAverageGpa()
  62. {
  63. Console.WriteLine("Calculating average GPA......");
  64. // Search and aggregate
  65. // Size 0 means documents are not returned, only aggregation is returned
  66. var aggResponse = await osClient.SearchAsync<Student>(s => s
  67. .Index(index)
  68. .Size(0)
  69. .Aggregations(a => a
  70. .Average("average gpa",
  71. avg => avg.Field(fld => fld.Gpa))));
  72. if (!aggResponse.IsValid) throw new Exception("Aggregation response not valid");
  73. var avg = aggResponse.Aggregations.Average("average gpa").Value;
  74. Console.WriteLine($"Average GPA is {avg}");
  75. }
  76. }

copy

More advanced features of the high-level .NET client - 图1