Low-level .NET client (OpenSearch.Net)

OpenSearch.Net is a low-level .NET client that provides the foundational layer of communication with OpenSearch. It is dependency free, and it can handle round-robin load balancing, transport, and the basic request/response cycle. OpenSearch.Net contains all OpenSearch API endpoints as methods. When using OpenSearch.Net, you need to construct the queries yourself.

This getting started guide illustrates how to connect to OpenSearch, index documents, and run queries. For the client source code, see the opensearch-net repo.

Example

The following example illustrates connecting to OpenSearch, indexing documents, and sending queries on the data. It uses the Student class to represent one student, which is equivalent to one document in the index.

  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

Installing the Opensearch.Net client

To install Opensearch.Net, download the Opensearch.Net NuGet package and add it to your project in an IDE of your choice. In Microsoft Visual Studio, follow the steps below:

  • In the Solution Explorer panel, right-click on your solution or project and select Manage NuGet Packages for Solution.
  • Search for the OpenSearch.Net NuGet package, and select Install.

Alternatively, you can add OpenSearch.Net to your .csproj file:

  1. <Project>
  2. ...
  3. <ItemGroup>
  4. <PackageReference Include="Opensearch.Net" Version="1.0.0" />
  5. </ItemGroup>
  6. </Project>

copy

Connecting to OpenSearch

Use the default constructor when creating an OpenSearchLowLevelClient object to connect to the default OpenSearch host (http://localhost:9200).

  1. var client = new OpenSearchLowLevelClient();

copy

To connect to your OpenSearch cluster through a single node with a known address, create a ConnectionConfiguration object with that address and pass it to the OpenSearch.Net constructor:

  1. var nodeAddress = new Uri("http://myserver:9200");
  2. var config = new ConnectionConfiguration(nodeAddress);
  3. var client = new OpenSearchLowLevelClient(config);

copy

You can also use a connection pool to manage the nodes in the cluster. Additionally, you can set up a connection configuration to have OpenSearch return the response as formatted JSON.

  1. var uri = new Uri("http://localhost:9200");
  2. var connectionPool = new SingleNodeConnectionPool(uri);
  3. var settings = new ConnectionConfiguration(connectionPool).PrettyJson();
  4. var client = new OpenSearchLowLevelClient(settings);

copy

To connect to your OpenSearch cluster using multiple nodes, create a connection pool with their addresses. In this example, a SniffingConnectionPool is used because it keeps track of nodes being removed or added to the cluster, so it works best for clusters that scale automatically.

  1. var uris = new[]
  2. {
  3. new Uri("http://localhost:9200"),
  4. new Uri("http://localhost:9201"),
  5. new Uri("http://localhost:9202")
  6. };
  7. var connectionPool = new SniffingConnectionPool(uris);
  8. var settings = new ConnectionConfiguration(connectionPool).PrettyJson();
  9. var client = new OpenSearchLowLevelClient(settings);

copy

Using ConnectionSettings

ConnectionConfiguration is used to pass configuration options to the OpenSearch.Net client. ConnectionSettings inherits from ConnectionConfiguration and provides additional configuration options. The following example uses ConnectionSettings to:

  • Set the default index name for requests that don’t specify the index name.
  • Enable gzip-compressed requests and responses.
  • Signal to OpenSearch to return formatted JSON.
  • Make field names lowercase.
  1. var uri = new Uri("http://localhost:9200");
  2. var connectionPool = new SingleNodeConnectionPool(uri);
  3. var settings = new ConnectionSettings(connectionPool)
  4. .DefaultIndex("students")
  5. .EnableHttpCompression()
  6. .PrettyJson()
  7. .DefaultFieldNameInferrer(f => f.ToLower());
  8. var client = new OpenSearchLowLevelClient(settings);

copy

Indexing one document

To index a document, you first need to create an instance of the Student class:

  1. var student = new Student {
  2. Id = 100,
  3. FirstName = "Paulo",
  4. LastName = "Santos",
  5. Gpa = 3.93,
  6. GradYear = 2021
  7. };

copy

Alternatively, you can create an instance of Student using an anonymous type:

  1. var student = new {
  2. Id = 100,
  3. FirstName = "Paulo",
  4. LastName = "Santos",
  5. Gpa = 3.93,
  6. GradYear = 2021
  7. };

copy

Next, upload this Student into the students index using the Index method:

  1. var response = client.Index<StringResponse>("students", "100",
  2. PostData.Serializable(student));
  3. Console.WriteLine(response.Body);

copy

The generic type parameter of the Index method specifies the response body type. In the example above, the response is a string.

Indexing many documents using the Bulk API

To index many documents, use the Bulk API to bundle many operations into one request:

  1. var studentArray = new object[]
  2. {
  3. new {index = new { _index = "students", _type = "_doc", _id = "200"}},
  4. new { Id = 200,
  5. FirstName = "Shirley",
  6. LastName = "Rodriguez",
  7. Gpa = 3.91,
  8. GradYear = 2019
  9. },
  10. new {index = new { _index = "students", _type = "_doc", _id = "300"}},
  11. new { Id = 300,
  12. FirstName = "Nikki",
  13. LastName = "Wolf",
  14. Gpa = 3.87,
  15. GradYear = 2020
  16. }
  17. };
  18. var manyResponse = client.Bulk<StringResponse>(PostData.MultiJson(studentArray));

copy

You can send the request body as an anonymous object, string, byte array, or stream in APIs that take a body. For APIs that take multiline JSON, you can send the body as a list of bytes or a list of objects, like in the example above. The PostData class has static methods to send the body in all of these forms.

Searching for a document

To construct a Query DSL query, use anonymous types within the request body. The following query searches for all students who graduated in 2021:

  1. var searchResponseLow = client.Search<StringResponse>("students",
  2. PostData.Serializable(
  3. new
  4. {
  5. from = 0,
  6. size = 20,
  7. query = new
  8. {
  9. term = new
  10. {
  11. gradYear = new
  12. {
  13. value = 2019
  14. }
  15. }
  16. }
  17. }));
  18. Console.WriteLine(searchResponseLow.Body);

copy

Alternatively, you can use strings to construct the request. When using strings, you have to escape the " character:

  1. var searchResponse = client.Search<StringResponse>("students",
  2. @" {
  3. ""query"":
  4. {
  5. ""match"":
  6. {
  7. ""lastName"":
  8. {
  9. ""query"": ""Santos""
  10. }
  11. }
  12. }
  13. }");
  14. Console.WriteLine(searchResponse.Body);

copy

Using OpenSearch.Net methods asynchronously

For applications that require asynchronous code, all method calls in OpenSearch.Client have asynchronous counterparts:

  1. // synchronous method
  2. var response = client.Index<StringResponse>("students", "100",
  3. PostData.Serializable(student));
  4. // asynchronous method
  5. var response = client.IndexAsync<StringResponse>("students", "100",
  6. PostData.Serializable(student));

copy

Handling exceptions

By default, OpenSearch.Net does not throw exceptions when an operation is unsuccessful. In particular, OpenSearch.Net does not throw exceptions if the response status code has one of the expected values for this request. For example, the following query searches for a document in an index that does not exist:

  1. var searchResponse = client.Search<StringResponse>("students1",
  2. @" {
  3. ""query"":
  4. {
  5. ""match"":
  6. {
  7. ""lastName"":
  8. {
  9. ""query"": ""Santos""
  10. }
  11. }
  12. }
  13. }");
  14. Console.WriteLine(searchResponse.Body);

copy

The response contains an error status code 404, which is one of the expected error codes for search requests, so no exception is thrown. You can see the status code in the status field:

  1. {
  2. "error" : {
  3. "root_cause" : [
  4. {
  5. "type" : "index_not_found_exception",
  6. "reason" : "no such index [students1]",
  7. "index" : "students1",
  8. "resource.id" : "students1",
  9. "resource.type" : "index_or_alias",
  10. "index_uuid" : "_na_"
  11. }
  12. ],
  13. "type" : "index_not_found_exception",
  14. "reason" : "no such index [students1]",
  15. "index" : "students1",
  16. "resource.id" : "students1",
  17. "resource.type" : "index_or_alias",
  18. "index_uuid" : "_na_"
  19. },
  20. "status" : 404
  21. }

To configure OpenSearch.Net to throw exceptions, turn on the ThrowExceptions() setting on ConnectionConfiguration:

  1. var uri = new Uri("http://localhost:9200");
  2. var connectionPool = new SingleNodeConnectionPool(uri);
  3. var settings = new ConnectionConfiguration(connectionPool)
  4. .PrettyJson().ThrowExceptions();
  5. var client = new OpenSearchLowLevelClient(settings);

copy

You can use the following properties of the response object to determine response success:

  1. Console.WriteLine("Success: " + searchResponse.Success);
  2. Console.WriteLine("SuccessOrKnownError: " + searchResponse.SuccessOrKnownError);
  3. Console.WriteLine("Original Exception: " + searchResponse.OriginalException);
  • Success returns true if the response code is in the 2xx range or the response code has one of the expected values for this request.
  • SuccessOrKnownError returns true if the response is successful or the response code is in the 400–501 or 505–599 ranges. If SuccessOrKnownError is true, the request is not retried.
  • OriginalException holds the original exception for the unsuccessful responses.

Sample program

The following program creates an index, indexes data, and searches for documents.

  1. using OpenSearch.Net;
  2. using OpenSearch.Client;
  3. namespace NetClientProgram;
  4. internal class Program
  5. {
  6. public static void Main(string[] args)
  7. {
  8. // Create a client with custom settings
  9. var uri = new Uri("http://localhost:9200");
  10. var connectionPool = new SingleNodeConnectionPool(uri);
  11. var settings = new ConnectionSettings(connectionPool)
  12. .PrettyJson();
  13. var client = new OpenSearchLowLevelClient(settings);
  14. Console.WriteLine("Indexing one student......");
  15. var student = new Student {
  16. Id = 100,
  17. FirstName = "Paulo",
  18. LastName = "Santos",
  19. Gpa = 3.93,
  20. GradYear = 2021 };v
  21. var response = client.Index<StringResponse>("students", "100",
  22. PostData.Serializable(student));
  23. Console.WriteLine(response.Body);
  24. Console.WriteLine("Indexing many students......");
  25. var studentArray = new object[]
  26. {
  27. new { index = new { _index = "students", _type = "_doc", _id = "200"}},
  28. new {
  29. Id = 200,
  30. FirstName = "Shirley",
  31. LastName = "Rodriguez",
  32. Gpa = 3.91,
  33. GradYear = 2019},
  34. new { index = new { _index = "students", _type = "_doc", _id = "300"}},
  35. new {
  36. Id = 300,
  37. FirstName = "Nikki",
  38. LastName = "Wolf",
  39. Gpa = 3.87,
  40. GradYear = 2020}
  41. };
  42. var manyResponse = client.Bulk<StringResponse>(PostData.MultiJson(studentArray));
  43. Console.WriteLine(manyResponse.Body);
  44. Console.WriteLine("Searching for students who graduated in 2019......");
  45. var searchResponseLow = client.Search<StringResponse>("students",
  46. PostData.Serializable(
  47. new
  48. {
  49. from = 0,
  50. size = 20,
  51. query = new
  52. {
  53. term = new
  54. {
  55. gradYear = new
  56. {
  57. value = 2019
  58. }
  59. }
  60. }
  61. }));
  62. Console.WriteLine(searchResponseLow.Body);
  63. Console.WriteLine("Searching for a student with the last name Santos......");
  64. var searchResponse = client.Search<StringResponse>("students",
  65. @" {
  66. ""query"":
  67. {
  68. ""match"":
  69. {
  70. ""lastName"":
  71. {
  72. ""query"": ""Santos""
  73. }
  74. }
  75. }
  76. }");
  77. Console.WriteLine(searchResponse.Body);
  78. }
  79. }

copy