Adds Rust client documentation (#2342)

* Adds Rust client documentation

Signed-off-by: Fanit Kolchina <kolchfa@amazon.com>

* Added copy buttons and refactored more clients

Signed-off-by: Fanit Kolchina <kolchfa@amazon.com>

* Incorporated doc review comments

Signed-off-by: Fanit Kolchina <kolchfa@amazon.com>

* Incorporated doc review feedback

Signed-off-by: Fanit Kolchina <kolchfa@amazon.com>

* One more fix - indexes

Signed-off-by: Fanit Kolchina <kolchfa@amazon.com>

* Incorporated editorial comments

Signed-off-by: Fanit Kolchina <kolchfa@amazon.com>

Signed-off-by: Fanit Kolchina <kolchfa@amazon.com>
This commit is contained in:
kolchfa-aws 2023-01-10 13:49:15 -05:00 committed by GitHub
parent 9a0a059b7e
commit c25ff903a1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
16 changed files with 791 additions and 36 deletions

View File

@ -10,7 +10,7 @@ parent: .NET clients
OpenSearch.Client is a high-level .NET client. It provides strongly typed requests and responses as well as Query DSL. It frees you from constructing raw JSON requests and parsing raw JSON responses by providing models that parse and serialize/deserialize requests and responses automatically. OpenSearch.Client also exposes the OpenSearch.Net low-level client if you need it.
This getting started guide illustrates how to connect to OpenSearch, index documents, and run queries.
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](https://github.com/opensearch-project/opensearch-net).
## Installing OpenSearch.Client
@ -27,6 +27,7 @@ Alternatively, you can add OpenSearch.Client to your .csproj file:
</ItemGroup>
</Project>
```
{% include copy.html %}
## Example
@ -42,6 +43,7 @@ public class Student
public double Gpa { get; init; }
}
```
{% include copy.html %}
By default, OpenSearch.Client uses camel case to convert property names to field names.
{: .note}
@ -53,6 +55,7 @@ Use the default constructor when creating an OpenSearchClient object to connect
```cs
var client = new OpenSearchClient();
```
{% include copy.html %}
To connect to your OpenSearch cluster through a single node with a known address, specify this address when creating an instance of OpenSearch.Client:
@ -60,6 +63,7 @@ To connect to your OpenSearch cluster through a single node with a known address
var nodeAddress = new Uri("http://myserver:9200");
var client = new OpenSearchClient(nodeAddress);
```
{% include copy.html %}
You can also connect to OpenSearch through multiple nodes. Connecting to your OpenSearch cluster with a node pool provides advantages like load balancing and cluster failover support. To connect to your OpenSearch cluster using multiple nodes, specify their addresses and create a `ConnectionSettings` object for the OpenSearch.Client instance:
@ -75,6 +79,7 @@ var pool = new StaticConnectionPool(nodes);
var settings = new ConnectionSettings(pool);
var client = new OpenSearchClient(settings);
```
{% include copy.html %}
## Using ConnectionSettings
@ -86,6 +91,7 @@ var node = new Uri("http://myserver:9200");
var config = new ConnectionSettings(node).DefaultIndex("students");
var client = new OpenSearchClient(config);
```
{% include copy.html %}
## Indexing one document
@ -94,6 +100,7 @@ Create one instance of Student:
```cs
var student = new Student { Id = 100, FirstName = "Paulo", LastName = "Santos", Gpa = 3.93, GradYear = 2021 };
```
{% include copy.html %}
To index one document, you can use either fluent lambda syntax or object initializer syntax.
@ -102,11 +109,14 @@ Index this Student into the `students` index using fluent lambda syntax:
```cs
var response = client.Index(student, i => i.Index("students"));
```
{% include copy.html %}
Index this Student into the `students` index using object initializer syntax:
```cs
var response = client.Index(new IndexRequest<Student>(student, "students"));
```
{% include copy.html %}
## Indexing many documents
@ -121,6 +131,7 @@ var studentArray = new Student[]
var manyResponse = client.IndexMany(studentArray, "students");
```
{% include copy.html %}
## Searching for a document
@ -162,6 +173,7 @@ var searchResponse = client.Search<Student>(s => s
.Field(fld => fld.LastName)
.Query("Santos"))));
```
{% include copy.html %}
You can print out the results by accessing the documents in the response:
@ -174,6 +186,7 @@ if (searchResponse.IsValid)
}
}
```
{% include copy.html %}
The response contains one document, which corresponds to the correct student:
@ -222,6 +235,7 @@ if (searchResponseLow.IsValid)
}
}
```
{% include copy.html %}
## Sample program
@ -326,4 +340,4 @@ internal class Program
}
}
```
{% include copy.html %}

View File

@ -20,6 +20,7 @@ public class Student
public double Gpa { get; init; }
}
```
{% include copy.html %}
## Mappings
@ -31,6 +32,7 @@ Similarly, OpenSearch.Client uses auto mapping to infer field data types based o
var createResponse = await osClient.Indices.CreateAsync("students",
c => c.Map(m => m.AutoMap<Student>()));
```
{% include copy.html %}
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:
@ -59,6 +61,7 @@ var createResponse = await osClient.Indices.CreateAsync(index,
.Keyword(k => k.Name(f => f.FirstName))
.Keyword(k => k.Name(f => f.LastName)))));
```
{% include copy.html %}
## Settings
@ -94,6 +97,7 @@ var createResponse = await osClient.Indices.CreateAsync(index,
.Keyword(k => k.Name(f => f.LastName))))
.Settings(s => s.NumberOfShards(1).NumberOfReplicas(2)));
```
{% include copy.html %}
## Indexing multiple documents using the Bulk API
@ -114,6 +118,7 @@ var bulkAll = osClient.BulkAll(ReadData(), r => r
.MaxDegreeOfParallelism(4)
.Size(100));
```
{% include copy.html %}
## Searching with Boolean query
@ -131,6 +136,7 @@ var gradResponse = await osClient.SearchAsync<Student>(s => s
.Term(t => t.Field(fld => fld.GradYear).Value(2022)))))
.Sort(srt => srt.Ascending(f => f.LastName)));
```
{% include copy.html %}
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.
@ -149,6 +155,7 @@ var aggResponse = await osClient.SearchAsync<Student>(s => s
.Average("average gpa",
avg => avg.Field(fld => fld.Gpa))));
```
{% include copy.html %}
## Sample program for creating an index and indexing data
@ -215,6 +222,7 @@ internal class Program
}
}
```
{% include copy.html %}
## Sample program for search
@ -316,4 +324,5 @@ internal class Program
Console.WriteLine($"Average GPA is {avg}");
}
}
```
```
{% include copy.html %}

View File

@ -10,6 +10,8 @@ parent: .NET clients
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](https://github.com/opensearch-project/opensearch-net).
## 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.
@ -24,6 +26,7 @@ public class Student
public double Gpa { get; init; }
}
```
{% include copy.html %}
## Installing the Opensearch.Net client
@ -32,6 +35,7 @@ To install Opensearch.Net, download the [Opensearch.Net NuGet package](https://w
- Search for the OpenSearch.Net NuGet package, and select **Install**.
Alternatively, you can add OpenSearch.Net to your .csproj file:
```xml
<Project>
...
@ -40,6 +44,7 @@ Alternatively, you can add OpenSearch.Net to your .csproj file:
</ItemGroup>
</Project>
```
{% include copy.html %}
## Connecting to OpenSearch
@ -48,6 +53,7 @@ Use the default constructor when creating an OpenSearchLowLevelClient object to
```cs
var client = new OpenSearchLowLevelClient();
```
{% include copy.html %}
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:
@ -56,6 +62,7 @@ var nodeAddress = new Uri("http://myserver:9200");
var config = new ConnectionConfiguration(nodeAddress);
var client = new OpenSearchLowLevelClient(config);
```
{% include copy.html %}
You can also use a [connection pool]({{site.url}}{{site.baseurl}}/clients/dot-net-conventions#connection-pools) to manage the nodes in the cluster. Additionally, you can set up a connection configuration to have OpenSearch return the response as formatted JSON.
@ -65,6 +72,7 @@ var connectionPool = new SingleNodeConnectionPool(uri);
var settings = new ConnectionConfiguration(connectionPool).PrettyJson();
var client = new OpenSearchLowLevelClient(settings);
```
{% include copy.html %}
To connect to your OpenSearch cluster using multiple nodes, create a connection pool with their addresses. In this example, a [`SniffingConnectionPool`]({{site.url}}{{site.baseurl}}/clients/dot-net-conventions#connection-pools) is used because it keeps track of nodes being removed or added to the cluster, so it works best for clusters that scale automatically.
@ -79,6 +87,7 @@ var connectionPool = new SniffingConnectionPool(uris);
var settings = new ConnectionConfiguration(connectionPool).PrettyJson();
var client = new OpenSearchLowLevelClient(settings);
```
{% include copy.html %}
## Using ConnectionSettings
@ -100,6 +109,8 @@ var settings = new ConnectionSettings(connectionPool)
var client = new OpenSearchLowLevelClient(settings);
```
{% include copy.html %}
## Indexing one document
To index a document, you first need to create an instance of the Student class:
@ -113,6 +124,7 @@ var student = new Student {
GradYear = 2021
};
```
{% include copy.html %}
Alternatively, you can create an instance of Student using an anonymous type:
@ -125,6 +137,8 @@ var student = new {
GradYear = 2021
};
```
{% include copy.html %}
Next, upload this Student into the `students` index using the `Index` method:
```cs
@ -132,6 +146,7 @@ var response = client.Index<StringResponse>("students", "100",
PostData.Serializable(student));
Console.WriteLine(response.Body);
```
{% include copy.html %}
The generic type parameter of the `Index` method specifies the response body type. In the example above, the response is a string.
@ -160,6 +175,7 @@ var studentArray = new object[]
var manyResponse = client.Bulk<StringResponse>(PostData.MultiJson(studentArray));
```
{% include copy.html %}
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.
@ -189,6 +205,7 @@ var searchResponseLow = client.Search<StringResponse>("students",
Console.WriteLine(searchResponseLow.Body);
```
{% include copy.html %}
Alternatively, you can use strings to construct the request. When using strings, you have to escape the `"` character:
@ -209,6 +226,7 @@ var searchResponse = client.Search<StringResponse>("students",
Console.WriteLine(searchResponse.Body);
```
{% include copy.html %}
## Using OpenSearch.Net methods asynchronously
@ -223,6 +241,7 @@ var response = client.Index<StringResponse>("students", "100",
var response = client.IndexAsync<StringResponse>("students", "100",
PostData.Serializable(student));
```
{% include copy.html %}
## Handling exceptions
@ -245,6 +264,7 @@ var searchResponse = client.Search<StringResponse>("students1",
Console.WriteLine(searchResponse.Body);
```
{% include copy.html %}
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:
@ -281,6 +301,7 @@ var settings = new ConnectionConfiguration(connectionPool)
.PrettyJson().ThrowExceptions();
var client = new OpenSearchLowLevelClient(settings);
```
{% include copy.html %}
You can use the following properties of the response object to determine response success:
@ -393,3 +414,4 @@ internal class Program
}
}
```
{% include copy.html %}

View File

@ -30,6 +30,7 @@ To create a node, pass a `Uri` object into its constructor:
var uri = new Uri("http://example.org/opensearch");
var node = new Node(uri);
```
{% include copy.html %}
When first created, a node is master eligible, and its `HoldsData` property is set to true.
The `AbsolutePath` property of the node created above is `"/opensearch/"`: A trailing forward slash is appended so that the paths can be easily combined. If not specified, the default `Port` is 80.
@ -76,6 +77,7 @@ To set the maximum number of retries, specify the number in the `MaximumRetries`
```cs
var settings = new ConnectionSettings(connectionPool).MaximumRetries(5);
```
{% include copy.html %}
You can also set a `RequestTimeout` that specifies a timeout for a single request and a `MaxRetryTimeout` that specifies the time limit for all retry attempts. In the example below, `RequestTimeout` is set to 4 seconds, and `MaxRetryTimeout` is set to 12 seconds, so the maximum number of attempts for a query is 3.
@ -84,6 +86,7 @@ var settings = new ConnectionSettings(connectionPool)
.RequestTimeout(TimeSpan.FromSeconds(4))
.MaxRetryTimeout(TimeSpan.FromSeconds(12));
```
{% include copy.html %}
## Failover

View File

@ -6,7 +6,7 @@ nav_order: 50
# Go client
The OpenSearch Go client lets you connect your Go application with the data in your OpenSearch cluster.
The OpenSearch Go client lets you connect your Go application with the data in your OpenSearch cluster. This getting started guide illustrates how to connect to OpenSearch, index documents, and run queries. For the client source code, see the [opensearch-go repo](https://github.com/opensearch-project/opensearch-go).
## Setup
@ -16,12 +16,15 @@ If you're starting a new project, create a new module by running the following c
```go
go mod init <mymodulename>
```
{% include copy.html %}
To add the Go client to your project, import it like any other module:
```go
go get github.com/opensearch-project/opensearch-go
```
{% include copy.html %}
## Connecting to OpenSearch
To connect to the default OpenSearch host, create a client object with the address `https://localhost:9200` if you are using the Security plugin:
@ -36,6 +39,7 @@ client, err := opensearch.NewClient(opensearch.Config{
Password: "admin",
})
```
{% include copy.html %}
If you are not using the Security plugin, create a client object with the address `http://localhost:9200`:
@ -47,6 +51,7 @@ client, err := opensearch.NewClient(opensearch.Config{
Addresses: []string{"http://localhost:9200"},
})
```
{% include copy.html %}
The Go client constructor takes an `opensearch.Config{}` type, which can be customized using options such as a list of OpenSearch node addresses or a username and password combination.
@ -64,6 +69,7 @@ client, err := opensearch.NewClient(opensearch.Config{
Addresses: urls,
})
```
{% include copy.html %}
The Go client retries requests for a maximum of three times by default. To customize the number of retries, set the `MaxRetries` parameter. Additionally, you can change the list of response codes for which a request is retried by setting the `RetryOnStatus` parameter. The following code snippet creates a new Go client with custom `MaxRetries` and `RetryOnStatus` values:
@ -77,6 +83,7 @@ client, err := opensearch.NewClient(opensearch.Config{
RetryOnStatus: []int{502, 503, 504},
})
```
{% include copy.html %}
## Creating an index
@ -97,6 +104,7 @@ res := opensearchapi.IndicesCreateRequest{
Body: settings,
}
```
{% include copy.html %}
## Indexing a document
@ -117,6 +125,7 @@ req := opensearchapi.IndexRequest{
}
insertResponse, err := req.Do(context.Background(), client)
```
{% include copy.html %}
## Performing bulk operations
@ -134,10 +143,11 @@ blk, err := client.Bulk(
`),
)
```
{% include copy.html %}
## Searching for documents
The easiest way to search for documents is to construct a query string. The following code uses a `multi_match` query to search for "miller" in the title and director fields. It boosts the documents where "miller" is in the title field.
The easiest way to search for documents is to construct a query string. The following code uses a `multi_match` query to search for "miller" in the title and director fields. It boosts the documents where "miller" appears in the title field:
```go
content := strings.NewReader(`{
@ -157,6 +167,7 @@ search := opensearchapi.SearchRequest{
searchResponse, err := search.Do(context.Background(), client)
```
{% include copy.html %}
## Deleting a document
@ -170,6 +181,7 @@ delete := opensearchapi.DeleteRequest{
deleteResponse, err := delete.Do(context.Background(), client)
```
{% include copy.html %}
## Deleting an index
@ -182,10 +194,11 @@ deleteIndex := opensearchapi.IndicesDeleteRequest{
deleteIndexResponse, err := deleteIndex.Do(context.Background(), client)
```
{% include copy.html %}
## Sample program
This sample program creates a client, adds an index with non-default settings, inserts a document, performs bulk operations, searches for the document, deletes the document, and, finally, deletes the index:
The following sample program creates a client, adds an index with non-default settings, inserts a document, performs bulk operations, searches for the document, deletes the document, and then deletes the index:
```go
package main
@ -328,3 +341,4 @@ func main() {
fmt.Println(deleteIndexResponse)
}
```
{% include copy.html %}

View File

@ -36,7 +36,7 @@ You can now point your Java client to the truststore and set basic authenticatio
If you run into issues when configuring security, see [common issues]({{site.url}}{{site.baseurl}}/troubleshoot/index) and [troubleshoot TLS]({{site.url}}{{site.baseurl}}/troubleshoot/tls).
## Sample code
## Sample program
This code example uses basic credentials that come with the default OpenSearch configuration. If youre using the OpenSearch Java high-level REST client with your own OpenSearch cluster, be sure to change the code to use your own credentials.

View File

@ -6,15 +6,15 @@ nav_order: 30
# Java client
The OpenSearch Java client allows you to interact with your OpenSearch clusters through Java methods and data structures rather than HTTP methods and raw JSON.
The OpenSearch Java client allows you to interact with your OpenSearch clusters through Java methods and data structures rather than HTTP methods and raw JSON. For example, you can submit requests to your cluster using objects to create indexes, add data to documents, or complete some other operation using the client's built-in methods.
For example, you can submit requests to your cluster using objects to create indices, add data to documents, or complete some other operation using the client's built-in methods.
This getting started guide illustrates how to connect to OpenSearch, index documents, and run queries. For the client source code, see the [opensearch-java repo](https://github.com/opensearch-project/opensearch-java).
## Install the client
## Installing the client
To start using the OpenSearch Java client, ensure that you have the following dependencies in your project's `pom.xml` file:
```
```xml
<dependency>
<groupId>org.opensearch.client</groupId>
<artifactId>opensearch-rest-client</artifactId>
@ -26,6 +26,7 @@ To start using the OpenSearch Java client, ensure that you have the following de
<version>2.0.0</version>
</dependency>
```
{% include copy.html %}
If you're using Gradle, add the following dependencies to your project.
@ -35,6 +36,7 @@ dependencies {
implementation 'org.opensearch.client:opensearch-java:2.0.0'
}
```
{% include copy.html %}
You can now start your OpenSearch cluster.
@ -47,6 +49,7 @@ If you're using certificates from a trusted Certificate Authority (CA), you don'
```bash
keytool -import <path-to-cert> -alias <alias-to-call-cert> -keystore <truststore-name>
```
{% include copy.html %}
You can now point your Java client to the truststore and set basic authentication credentials that can access a secure cluster (refer to the sample code below on how to do so).
@ -90,10 +93,11 @@ static class IndexData {
}
}
```
{% include copy.html %}
## Initialize the client with SSL and TLS enabled
## Initializing the client with SSL and TLS enabled
This code example uses basic credentials that come with the default OpenSearch configuration. If youre using the Java client with your own OpenSearch cluster, be sure to change the code to use your own credentials.
This code example uses basic credentials that come with the default OpenSearch configuration. If youre using the Java client with your own OpenSearch cluster, be sure to change the code so that it uses your own credentials.
The following sample code initializes a client with SSL and TLS enabled:
@ -144,12 +148,11 @@ public class OpenSearchClientExample {
}
}
```
{% include copy.html %}
## OpenSearch client examples
## Creating an index
This section has sample code that shows you how to create an index with non-default settings, add a document to the index, search for the document, delete the document, and finally delete the index.
### Create an index with non-default settings
You can create an index with non-default settings using the following code:
```java
String index = "sample-index";
@ -161,16 +164,22 @@ IndexSettingsBody settingsBody = new IndexSettingsBody.Builder().settings(indexS
PutSettingsRequest putSettingsRequest = new PutSettingsRequest.Builder().index(index).value(settingsBody).build();
client.indices().putSettings(putSettingsRequest);
```
{% include copy.html %}
### Index data
## Indexing data
You can index data into OpenSearch using the following code:
```java
IndexData indexData = new IndexData("first_name", "Bruce");
IndexRequest<IndexData> indexRequest = new IndexRequest.Builder<IndexData>().index(index).id("1").value(indexData).build();
client.index(indexRequest);
```
{% include copy.html %}
### Search for the document
## Searching for documents
You can search for a document using the following code:
```java
SearchResponse<IndexData> searchResponse = client.search(s -> s.index(index), IndexData.class);
@ -178,16 +187,20 @@ for (int i = 0; i< searchResponse.hits().hits().size(); i++) {
System.out.println(searchResponse.hits().hits().get(i).source());
}
```
{% include copy.html %}
### Delete the document
## Deleting a document
The following sample code deletes a document whose ID is 1.
The following sample code deletes a document whose ID is 1:
```java
client.delete(b -> b.index(index).id("1"));
```
{% include copy.html %}
### Delete the index
### Deleting an index
The following sample code deletes an index:
```java
DeleteRequest deleteRequest = new DeleteRequest.Builder().index(index).build();
@ -207,8 +220,11 @@ DeleteResponse deleteResponse = client.indices().delete(deleteRequest);
}
}
```
{% include copy.html %}
## Complete code sample
## Sample program
The following sample program creates a client, adds an index with non-default settings, inserts a document, searches for the document, deletes the document, and then deletes the index:
```java
import org.apache.http.HttpHost;
@ -297,3 +313,4 @@ public class OpenSearchClientExample {
}
}
```
{% include copy.html %}

View File

@ -34,6 +34,7 @@ const result = await client.helpers.bulk({
console.log(result)
```
{% include copy.html %}
Bulk helper operations return an object with the following fields:
@ -85,6 +86,7 @@ client.helpers.bulk({
}
})
```
{% include copy.html %}
The following bulk operation indexes documents into `example-index` with document overwrite:
@ -101,6 +103,7 @@ client.helpers.bulk({
}
})
```
{% include copy.html %}
#### Create
@ -118,6 +121,7 @@ client.helpers.bulk({
}
})
```
{% include copy.html %}
The following bulk operation creates documents in the `example-index` with document overwrite:
@ -134,6 +138,7 @@ client.helpers.bulk({
}
})
```
{% include copy.html %}
#### Update
@ -156,6 +161,7 @@ client.helpers.bulk({
}
})
```
{% include copy.html %}
The following bulk operation updates documents in the `arrayOfDocuments` with document overwrite:
@ -175,6 +181,7 @@ client.helpers.bulk({
}
})
```
{% include copy.html %}
#### Delete
@ -192,3 +199,4 @@ client.helpers.bulk({
}
})
```
{% include copy.html %}

View File

@ -18,12 +18,14 @@ To add the client to your project, install it from [npm](https://www.npmjs.com):
```bash
npm install @opensearch-project/opensearch
```
{% include copy.html %}
To install a specific major version of the client, run the following command:
```bash
npm install @opensearch-project/opensearch@<version>
```
{% include copy.html %}
If you prefer to add the client manually or just want to examine the source code, see [opensearch-js](https://github.com/opensearch-project/opensearch-js) on GitHub.
@ -32,8 +34,133 @@ Then require the client:
```javascript
const { Client } = require("@opensearch-project/opensearch");
```
{% include copy.html %}
## Sample code
## Connecting to OpenSearch
To connect to the default OpenSearch host, create a client object with the address `https://localhost:9200` if you are using the Security plugin:
```javascript
var host = "localhost";
var protocol = "https";
var port = 9200;
var auth = "admin:admin"; // For testing only. Don't store credentials in code.
var ca_certs_path = "/full/path/to/root-ca.pem";
// Optional client certificates if you don't want to use HTTP basic authentication.
// var client_cert_path = '/full/path/to/client.pem'
// var client_key_path = '/full/path/to/client-key.pem'
// Create a client with SSL/TLS enabled.
var { Client } = require("@opensearch-project/opensearch");
var fs = require("fs");
var client = new Client({
node: protocol + "://" + auth + "@" + host + ":" + port,
ssl: {
ca: fs.readFileSync(ca_certs_path),
// You can turn off certificate verification (rejectUnauthorized: false) if you're using
// self-signed certificates with a hostname mismatch.
// cert: fs.readFileSync(client_cert_path),
// key: fs.readFileSync(client_key_path)
},
});
```
{% include copy.html %}
## Creating an index
To create an OpenSearch index, use the `indices.create()` method. You can use the following code to construct a JSON object with custom settings:
```javascript
var index_name = "books";
var settings = {
settings: {
index: {
number_of_shards: 4,
number_of_replicas: 3,
},
},
};
var response = await client.indices.create({
index: index_name,
body: settings,
});
```
{% include copy.html %}
## Indexing a document
You can index a document into OpenSearch using the client's `index` method:
```javascript
var document = {
title: "The Outsider",
author: "Stephen King",
year: "2018",
genre: "Crime fiction",
};
var id = "1";
var response = await client.index({
id: id,
index: index_name,
body: document,
refresh: true,
});
```
{% include copy.html %}
## Searching for documents
The easiest way to search for documents is to construct a query string. The following code uses a `match` query to search for "The Outsider" in the title field:
```javascript
var query = {
query: {
match: {
title: {
query: "The Outsider",
},
},
},
};
var response = await client.search({
index: index_name,
body: query,
});
```
{% include copy.html %}
## Deleting a document
You can delete a document using the client's `delete` method:
```javascript
var response = await client.delete({
index: index_name,
id: id,
});
```
{% include copy.html %}
## Deleting an index
You can delete an index using the `indices.delete()` method:
```javascript
var response = await client.indices.delete({
index: index_name,
});
```
{% include copy.html %}
## Sample program
The following sample program creates a client, adds an index with non-default settings, inserts a document, searches for the document, deletes the document, and then deletes the index:
```javascript
"use strict";
@ -55,7 +182,8 @@ var client = new Client({
node: protocol + "://" + auth + "@" + host + ":" + port,
ssl: {
ca: fs.readFileSync(ca_certs_path),
// You can turn off certificate verification (rejectUnauthorized: false) if you're using self-signed certificates with a hostname mismatch.
// You can turn off certificate verification (rejectUnauthorized: false) if you're using
// self-signed certificates with a hostname mismatch.
// cert: fs.readFileSync(client_cert_path),
// key: fs.readFileSync(client_key_path)
},
@ -64,6 +192,7 @@ var client = new Client({
async function search() {
// Create an index with non-default settings.
var index_name = "books";
var settings = {
settings: {
index: {
@ -140,8 +269,9 @@ async function search() {
search().catch(console.log);
```
{% include copy.html %}
## Authenticate with Amazon OpenSearch Service - AWS Sigv4
## Authenticating with Amazon OpenSearch Service AWS Sigv4
Use the following code to authenticate with AWS V2 SDK:
@ -175,6 +305,7 @@ const client = new Client({
node: "https://search-xxx.region.es.amazonaws.com", // OpenSearch domain URL
});
```
{% include copy.html %}
Use the following code to authenticate with AWS V3 SDK:
@ -202,6 +333,7 @@ const client = new Client({
node: "https://search-xxx.region.es.amazonaws.com", // OpenSearch domain URL
});
```
{% include copy.html %}
## Circuit breaker
@ -222,3 +354,4 @@ var client = new Client({
},
});
```
{% include copy.html %}

View File

@ -23,6 +23,7 @@ To add the client to your project, install it using [pip](https://pip.pypa.io/):
```bash
pip install opensearch-py-ml
```
{% include copy.html %}
Then import the client into OpenSearch like any other module:
@ -30,6 +31,7 @@ Then import the client into OpenSearch like any other module:
from opensearchpy import OpenSearch
import openseach_py_ml as oml
```
{% include copy.html %}
## API reference

View File

@ -6,9 +6,9 @@ nav_order: 70
# PHP client
The OpenSearch PHP client provides a safer and easier way to interact with your OpenSearch cluster. Rather than using OpenSearch from the browser and potentially exposing your data to the public, you can build an OpenSearch client that takes care of sending requests to your cluster.
The OpenSearch PHP client provides a safer and easier way to interact with your OpenSearch cluster. Rather than using OpenSearch from a browser and potentially exposing your data to the public, you can build an OpenSearch client that takes care of sending requests to your cluster. The client contains a library of APIs that let you perform different operations on your cluster and return a standard response body.
The client contains a library of APIs that let you perform different operations on your cluster and return a standard response body. The example here demonstrates some basic operations like creating an index, adding documents, and searching your data.
This getting started guide illustrates how to connect to OpenSearch, index documents, and run queries. For the client source code, see the [opensearch-php repo](https://github.com/opensearch-project/opensearch-php).
## Setup
@ -17,20 +17,121 @@ To add the client to your project, install it using [composer](https://getcompos
```bash
composer require opensearch-project/opensearch-php
```
{% include copy.html %}
To install a specific major version of the client, run the following command:
```bash
composer require opensearch-project/opensearch-php:<version>
```
{% include copy.html %}
Then require the autload file from composer in your code:
```php
require __DIR__ . '/vendor/autoload.php';
```
{% include copy.html %}
## Sample code
## Connecting to OpenSearch
To connect to the default OpenSearch host, create a client object with the address `https://localhost:9200` if you are using the Security plugin:
```php
$client = (new \OpenSearch\ClientBuilder())
->setHosts(['https://localhost:9200'])
->setBasicAuthentication('admin', 'admin') // For testing only. Don't store credentials in code.
->setSSLVerification(false) // For testing only. Use certificate for validation
->build();
```
{% include copy.html %}
## Creating an index
To create an OpenSearch index with custom settings, use the following code:
```php
$indexName = 'test-index-name';
// Create an index with non-default settings.
$client->indices()->create([
'index' => $indexName,
'body' => [
'settings' => [
'index' => [
'number_of_shards' => 4
]
]
]
]);
```
{% include copy.html %}
## Indexing a document
You can index a document into OpenSearch using the following code:
```php
$client->create([
'index' => $indexName,
'id' => 1,
'body' => [
'title' => 'Moneyball',
'director' => 'Bennett Miller',
'year' => 2011
]
]);
```
{% include copy.html %}
## Searching for documents
The following code uses a `multi_match` query to search for "miller" in the title and director fields. It boosts the documents where "miller" appears in the title field:
```php
var_dump(
$client->search([
'index' => $indexName,
'body' => [
'size' => 5,
'query' => [
'multi_match' => [
'query' => 'miller',
'fields' => ['title^2', 'director']
]
]
]
])
);
```
{% include copy.html %}
## Deleting a document
You can delete a document using the following code:
```php
$client->delete([
'index' => $indexName,
'id' => 1,
]);
```
{% include copy.html %}
## Deleting an index
You can delete an index using the following code:
```php
$client->indices()->delete([
'index' => $indexName
]);
```
{% include copy.html %}
## Sample program
The following sample program creates a client, adds an index with non-default settings, inserts a document, searches for the document, deletes the document, and then deletes the index:
```php
<?php
@ -97,4 +198,7 @@ $client->delete([
$client->indices()->delete([
'index' => $indexName
]);
?>
```
{% include copy.html %}

View File

@ -8,6 +8,8 @@ nav_order: 5
The OpenSearch high-level Python client (`opensearch-dsl-py`) provides wrapper classes for common OpenSearch entities, like documents, so you can work with them as Python objects. Additionally, the high-level client simplifies writing queries and supplies convenient Python methods for common OpenSearch operations. The high-level Python client supports creating and indexing documents, searching with and without filters, and updating documents using queries.
This getting started guide illustrates how to connect to OpenSearch, index documents, and run queries. For the client source code, see the [opensearch-dsl-py repo](https://github.com/opensearch-project/opensearch-dsl-py).
## Setup
To add the client to your project, install it using [pip](https://pip.pypa.io/):
@ -15,6 +17,7 @@ To add the client to your project, install it using [pip](https://pip.pypa.io/):
```bash
pip install opensearch-dsl
```
{% include copy.html %}
After installing the client, you can import it like any other module:
@ -22,8 +25,7 @@ After installing the client, you can import it like any other module:
from opensearchpy import OpenSearch
from opensearch_dsl import Search
```
If you prefer to add the client manually or just want to examine the source code, see [opensearch-dsl-py](https://github.com/opensearch-project/opensearch-dsl-py) on GitHub.
{% include copy.html %}
## Connecting to OpenSearch
@ -47,6 +49,7 @@ client = OpenSearch(
ca_certs = ca_certs_path
)
```
{% include copy.html %}
If you have your own client certificates, specify them in the `client_cert_path` and `client_key_path` parameters:
@ -74,6 +77,7 @@ client = OpenSearch(
ca_certs = ca_certs_path
)
```
{% include copy.html %}
If you are not using the Security plugin, create a client object with SSL disabled:
@ -91,6 +95,7 @@ client = OpenSearch(
ssl_show_warn = False
)
```
{% include copy.html %}
## Creating an index
@ -108,6 +113,7 @@ index_body = {
response = client.indices.create(index_name, body=index_body)
```
{% include copy.html %}
## Indexing a document
@ -125,6 +131,7 @@ class Movie(Document):
def save(self, ** kwargs):
return super(Movie, self).save(** kwargs)
```
{% include copy.html %}
To index a document, create an object of the new class and call its `save()` method:
@ -134,6 +141,7 @@ Movie.init(using=client)
doc = Movie(meta={'id': 1}, title='Moneyball', director='Bennett Miller', year='2011')
response = doc.save(using=client)
```
{% include copy.html %}
## Performing bulk operations
@ -144,6 +152,7 @@ movies = '{ "index" : { "_index" : "my-dsl-index", "_id" : "2" } } \n { "title"
client.bulk(movies)
```
{% include copy.html %}
## Searching for documents
@ -156,6 +165,7 @@ s = Search(using=client, index=index_name) \
response = s.execute()
```
{% include copy.html %}
The preceding query is equivalent to the following query in OpenSearch domain-specific language (DSL):
@ -189,6 +199,7 @@ response = client.delete(
id = '1'
)
```
{% include copy.html %}
## Deleting an index
@ -199,10 +210,11 @@ response = client.indices.delete(
index = 'my-dsl-index'
)
```
{% include copy.html %}
## Sample program
The following sample program creates a client, adds an index with non-default settings, inserts a document, performs bulk operations, searches for the document, deletes the document, and, finally, deletes the index:
The following sample program creates a client, adds an index with non-default settings, inserts a document, performs bulk operations, searches for the document, deletes the document, and then deletes the index:
```python
from opensearchpy import OpenSearch
@ -288,3 +300,4 @@ response = client.indices.delete(
print('\nDeleting index:')
print(response)
```
{% include copy.html %}

View File

@ -8,6 +8,8 @@ nav_order: 10
The OpenSearch low-level Python client (`opensearch-py`) provides wrapper methods for the OpenSearch REST API so that you can interact with your cluster more naturally in Python. Rather than sending raw HTTP requests to a given URL, you can create an OpenSearch client for your cluster and call the client's built-in functions.
This getting started guide illustrates how to connect to OpenSearch, index documents, and run queries. For the client source code, see the [opensearch-py repo](https://github.com/opensearch-project/opensearch-py).
## Setup
To add the client to your project, install it using [pip](https://pip.pypa.io/):
@ -15,14 +17,14 @@ To add the client to your project, install it using [pip](https://pip.pypa.io/):
```bash
pip install opensearch-py
```
{% include copy.html %}
After installing the client, you can import it like any other module:
```python
from opensearchpy import OpenSearch
```
If you prefer to add the client manually or just want to examine the source code, see [opensearch-py](https://github.com/opensearch-project/opensearch-py) on GitHub.
{% include copy.html %}
## Connecting to OpenSearch
@ -46,6 +48,7 @@ client = OpenSearch(
ca_certs = ca_certs_path
)
```
{% include copy.html %}
If you have your own client certificates, specify them in the `client_cert_path` and `client_key_path` parameters:
@ -73,6 +76,7 @@ client = OpenSearch(
ca_certs = ca_certs_path
)
```
{% include copy.html %}
If you are not using the Security plugin, create a client object with SSL disabled:
@ -90,6 +94,7 @@ client = OpenSearch(
ssl_show_warn = False
)
```
{% include copy.html %}
## Creating an index
@ -107,6 +112,7 @@ index_body = {
response = client.indices.create(index_name, body=index_body)
```
{% include copy.html %}
## Indexing a document
@ -126,6 +132,7 @@ response = client.index(
refresh = True
)
```
{% include copy.html %}
## Performing bulk operations
@ -136,6 +143,7 @@ movies = '{ "index" : { "_index" : "my-dsl-index", "_id" : "2" } } \n { "title"
client.bulk(movies)
```
{% include copy.html %}
## Searching for documents
@ -158,6 +166,7 @@ response = client.search(
index = 'python-test-index'
)
```
{% include copy.html %}
## Deleting a document
@ -169,6 +178,7 @@ response = client.delete(
id = '1'
)
```
{% include copy.html %}
## Deleting an index
@ -179,10 +189,11 @@ response = client.indices.delete(
index = 'python-test-index'
)
```
{% include copy.html %}
## Sample program
The following sample program creates a client, adds an index with non-default settings, inserts a document, performs bulk operations, searches for the document, deletes the document, and, finally, deletes the index:
The following sample program creates a client, adds an index with non-default settings, inserts a document, performs bulk operations, searches for the document, deletes the document, and then deletes the index:
```python
from opensearchpy import OpenSearch
@ -284,3 +295,4 @@ response = client.indices.delete(
print('\nDeleting index:')
print(response)
```
{% include copy.html %}

View File

@ -9,6 +9,8 @@ has_children: false
The OpenSearch Ruby client allows you to interact with your OpenSearch clusters through Ruby methods rather than HTTP methods and raw JSON.
This getting started guide illustrates how to connect to OpenSearch, index documents, and run queries. For the client source code, see the [opensearch-ruby repo](https://github.com/opensearch-project/opensearch-ruby).
## Installing the Ruby client
To install the Ruby gem for the Ruby client, run the following command:
@ -16,12 +18,14 @@ To install the Ruby gem for the Ruby client, run the following command:
```bash
gem install opensearch-ruby
```
{% include copy.html %}
To use the client, import it as a module:
```ruby
require 'opensearch'
```
{% include copy.html %}
## Connecting to OpenSearch
@ -30,6 +34,7 @@ To connect to the default OpenSearch host, create a client object, passing the d
```ruby
client = OpenSearch::Client.new(host: 'http://localhost:9200')
```
{% include copy.html %}
The following example creates a client object with a custom URL and the `log` option set to `true`. It sets the `retry_on_failure` parameter to retry a failed request five times rather than the default three times. Finally, it increases the timeout by setting the `request_timeout` parameter to 120 seconds. It then returns the basic cluster health information:
@ -43,6 +48,7 @@ client = OpenSearch::Client.new(
client.cluster.health
```
{% include copy.html %}
The output is as follows:
@ -89,6 +95,7 @@ client.indices.create(
body: index_body
)
```
{% include copy.html %}
## Mappings
@ -105,6 +112,7 @@ client.indices.put_mapping(
}
)
```
{% include copy.html %}
By default, string fields are mapped as `text`, but in the mapping above, the `first_name` and `last_name` fields are mapped as `keyword`. This mapping signals to OpenSearch that these fields should not be analyzed and should support only full case-sensitive matches.
@ -113,6 +121,7 @@ You can verify the index's mappings using the `get_mapping` method:
```ruby
response = client.indices.get_mapping(index: 'students')
```
{% include copy.html %}
If you know the mapping of your documents in advance and want to avoid mapping errors (for example, misspellings of a field name), you can set the `dynamic` parameter to `strict`:
@ -130,6 +139,7 @@ client.indices.put_mapping(
}
)
```
{% include copy.html %}
With strict mapping, you can index a document with a missing field, but you cannot index a document with a new field. For example, indexing the following document with a misspelled `grad_yea` field fails:
@ -148,6 +158,7 @@ client.index(
refresh: true
)
```
{% include copy.html %}
OpenSearch returns a mapping error:
@ -174,6 +185,7 @@ client.index(
refresh: true
)
```
{% include copy.html %}
## Updating a document
@ -185,6 +197,7 @@ client.update(index: 'students',
body: { doc: { gpa: 3.25 } },
refresh: true)
```
{% include copy.html %}
## Deleting a document
@ -197,6 +210,7 @@ client.delete(
refresh: true
)
```
{% include copy.html %}
## Bulk operations
@ -213,6 +227,7 @@ actions = [
]
client.bulk(body: actions, refresh: true)
```
{% include copy.html %}
You can delete multiple documents as follows:
@ -224,6 +239,7 @@ actions = [
]
client.bulk(body: actions, refresh: true)
```
{% include copy.html %}
You can perform different operations when using `bulk` as follows:
@ -240,6 +256,7 @@ actions = [
]
client.bulk(body: actions, refresh: true)
```
{% include copy.html %}
In the above example, you pass the data and the header together and you denote the data with the `data:` key.
@ -264,12 +281,14 @@ response = client.search(
index: 'students'
)
```
{% include copy.html %}
If you omit the request body in the `search` method, your query becomes a `match_all` query and returns all documents in the index:
```ruby
client.search(index: 'students')
```
{% include copy.html %}
## Boolean query
@ -296,6 +315,7 @@ query = {
response = client.search(index: 'students', from: 0, size: 10, body: query)
```
{% include copy.html %}
## Multi-search
@ -310,6 +330,7 @@ actions = [
]
response = client.msearch(index: 'students', body: actions)
```
{% include copy.html %}
## Scroll
@ -324,6 +345,7 @@ while response['hits']['hits'].size.positive?
response = client.scroll(scroll: '1m', body: { scroll_id: scroll_id })
end
```
{% include copy.html %}
First, you issue a search query, specifying the `scroll` and `size` parameters. The `scroll` parameter tells OpenSearch how long to keep the search context. In this case, it is set to two minutes. The `size` parameter specifies how many documents you want to return in each request.
@ -336,6 +358,7 @@ You can delete the index using the `delete` method:
```ruby
response = client.indices.delete(index: index_name)
```
{% include copy.html %}
## Sample program
@ -526,6 +549,7 @@ response = client.indices.delete(index: index_name)
puts MultiJson.dump(response, pretty: "true")
```
{% include copy.html %}
# Ruby AWS Sigv4 Client
@ -548,3 +572,4 @@ client.transport.reload_connections!
client.search q: 'test'
```
{% include copy.html %}

379
_clients/rust.md Normal file
View File

@ -0,0 +1,379 @@
---
layout: default
title: Rust client
nav_order: 100
---
# Rust client
The OpenSearch Rust client lets you connect your Rust application with the data in your OpenSearch cluster. For the client's complete API documentation and more examples, see the [OpenSearch docs.rs documentation](https://docs.rs/opensearch/).
This getting started guide illustrates how to connect to OpenSearch, index documents, and run queries. For the client source code, see the [opensearch-rs repo](https://github.com/opensearch-project/opensearch-rs).
## Setup
If you're starting a new project, add the `opensearch` crate to Cargo.toml:
```rust
[dependencies]
opensearch = "1.0.0"
```
{% include copy.html %}
Additionally, you may want to add the following `serde` dependencies that help serialize types to JSON and deserialize JSON responses:
```rust
serde = "~1"
serde_json = "~1"
```
{% include copy.html %}
The Rust client uses the higher-level [`reqwest`](https://crates.io/crates/reqwest) HTTP client library for HTTP requests, and reqwest uses the [`tokio`](https://crates.io/crates/tokio) platform to support asynchronous requests. If you are planning to use asynchronous functions, you need to add the `tokio` dependency to Cargo.toml:
```rust
tokio = { version = "*", features = ["full"] }
```
{% include copy.html %}
See the [Sample program](#sample-program) section for the complete Cargo.toml file.
To use the Rust client API, import the modules, structs, and enums you need:
```rust
use opensearch::OpenSearch;
```
{% include copy.html %}
## Connecting to OpenSearch
To connect to the default OpenSearch host, create a default client object that connects to OpenSearch at the address `http://localhost:9200`:
```rust
let client = OpenSearch::default();
```
{% include copy.html %}
To connect to an OpenSearch host that is running at a different address, create a client with the specified address:
```rust
let transport = Transport::single_node("http://localhost:9200")?;
let client = OpenSearch::new(transport);
```
{% include copy.html %}
Alternatively, you can customize the URL and use a connection pool by creating a `TransportBuilder` struct and passing it to `OpenSearch::new` to create a new instance of the client:
```rust
let url = Url::parse("http://localhost:9200")?;
let conn_pool = SingleNodeConnectionPool::new(url);
let transport = TransportBuilder::new(conn_pool).disable_proxy().build()?;
let client = OpenSearch::new(transport);
```
{% include copy.html %}
## Creating an index
To create an OpenSearch index, use the `create` function of the `opensearch::indices::Indices` struct. You can use the following code to construct a JSON object with custom mappings:
```rust
let response = client
.indices()
.create(IndicesCreateParts::Index("movies"))
.body(json!({
"mappings" : {
"properties" : {
"title" : { "type" : "text" }
}
}
}))
.send()
.await?;
```
{% include copy.html %}
## Indexing a document
You can index a document into OpenSearch using the client's `index` function:
```rust
let response = client
.index(IndexParts::IndexId("movies", "1"))
.body(json!({
"id": 1,
"title": "Moneyball",
"director": "Bennett Miller",
"year": "2011"
}))
.send()
.await?;
```
{% include copy.html %}
## Performing bulk operations
You can perform several operations at the same time by using the client's `bulk` function. First, create the JSON body of a Bulk API call, and then pass it to the `bulk` function:
```rust
let mut body: Vec<JsonBody<_>> = Vec::with_capacity(4);
// add the first operation and document
body.push(json!({"index": {"_id": "2"}}).into());
body.push(json!({
"id": 2,
"title": "Interstellar",
"director": "Christopher Nolan",
"year": "2014"
}).into());
// add the second operation and document
body.push(json!({"index": {"_id": "3"}}).into());
body.push(json!({
"id": 3,
"title": "Star Trek Beyond",
"director": "Justin Lin",
"year": "2015"
}).into());
let response = client
.bulk(BulkParts::Index("movies"))
.body(body)
.send()
.await?;
```
{% include copy.html %}
## Searching for documents
The easiest way to search for documents is to construct a query string. The following code uses a `multi_match` query to search for "miller" in the title and director fields. It boosts the documents where "miller" appears in the title field:
```rust
response = client
.search(SearchParts::Index(&["movies"]))
.from(0)
.size(10)
.body(json!({
"query": {
"multi_match": {
"query": "miller",
"fields": ["title^2", "director"]
}
}
}))
.send()
.await?;
```
{% include copy.html %}
You can then read the response body as JSON and iterate over the `hits` array to read all the `_source` documents:
```rust
let response_body = response.json::<Value>().await?;
for hit in response_body["hits"]["hits"].as_array().unwrap() {
// print the source document
println!("{}", serde_json::to_string_pretty(&hit["_source"]).unwrap());
}
```
{% include copy.html %}
## Deleting a document
You can delete a document using the client's `delete` function:
```rust
let response = client
.delete(DeleteParts::IndexId("movies", "2"))
.send()
.await?;
```
{% include copy.html %}
## Deleting an index
You can delete an index using the `delete` function of the `opensearch::indices::Indices` struct:
```rust
let response = client
.indices()
.delete(IndicesDeleteParts::Index(&["movies"]))
.send()
.await?;
```
{% include copy.html %}
## Sample program
The sample program uses the following Cargo.toml file with all dependencies described in the [Setup](#setup) section:
```rust
[package]
name = "os_rust_project"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
opensearch = "1.0.0"
tokio = { version = "*", features = ["full"] }
serde = "~1"
serde_json = "~1"
```
{% include copy.html %}
The following sample program creates a client, adds an index with non-default mappings, inserts a document, performs bulk operations, searches for the document, deletes the document, and then deletes the index:
```rust
use opensearch::{DeleteParts, OpenSearch, IndexParts, http::request::JsonBody, BulkParts, SearchParts};
use opensearch::{indices::{IndicesDeleteParts, IndicesCreateParts}};
use serde_json::{json, Value};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = OpenSearch::default();
// Create an index
let mut response = client
.indices()
.create(IndicesCreateParts::Index("movies"))
.body(json!({
"mappings" : {
"properties" : {
"title" : { "type" : "text" }
}
}
}))
.send()
.await?;
let mut successful = response.status_code().is_success();
if successful {
println!("Successfully created an index");
}
else {
println!("Could not create an index");
}
// Index a single document
println!("Indexing a single document...");
response = client
.index(IndexParts::IndexId("movies", "1"))
.body(json!({
"id": 1,
"title": "Moneyball",
"director": "Bennett Miller",
"year": "2011"
}))
.send()
.await?;
successful = response.status_code().is_success();
if successful {
println!("Successfully indexed a document");
}
else {
println!("Could not index document");
}
// Index multiple documents using the bulk operation
println!("Indexing multiple documents...");
let mut body: Vec<JsonBody<_>> = Vec::with_capacity(4);
// add the first operation and document
body.push(json!({"index": {"_id": "2"}}).into());
body.push(json!({
"id": 2,
"title": "Interstellar",
"director": "Christopher Nolan",
"year": "2014"
}).into());
// add the second operation and document
body.push(json!({"index": {"_id": "3"}}).into());
body.push(json!({
"id": 3,
"title": "Star Trek Beyond",
"director": "Justin Lin",
"year": "2015"
}).into());
response = client
.bulk(BulkParts::Index("movies"))
.body(body)
.send()
.await?;
let mut response_body = response.json::<Value>().await?;
successful = response_body["errors"].as_bool().unwrap() == false;
if successful {
println!("Successfully performed bulk operations");
}
else {
println!("Could not perform bulk operations");
}
// Search for a document
println!("Searching for a document...");
response = client
.search(SearchParts::Index(&["movies"]))
.from(0)
.size(10)
.body(json!({
"query": {
"multi_match": {
"query": "miller",
"fields": ["title^2", "director"]
}
}
}))
.send()
.await?;
response_body = response.json::<Value>().await?;
for hit in response_body["hits"]["hits"].as_array().unwrap() {
// print the source document
println!("{}", serde_json::to_string_pretty(&hit["_source"]).unwrap());
}
// Delete a document
response = client
.delete(DeleteParts::IndexId("movies", "2"))
.send()
.await?;
successful = response.status_code().is_success();
if successful {
println!("Successfully deleted a document");
}
else {
println!("Could not delete document");
}
// Delete the index
response = client
.indices()
.delete(IndicesDeleteParts::Index(&["movies"]))
.send()
.await?;
successful = response.status_code().is_success();
if successful {
println!("Successfully deleted the index");
}
else {
println!("Could not delete the index");
}
Ok(())
}
```
{% include copy.html %}

View File

@ -250,7 +250,7 @@ img {
.copy-button-wrap {
background-color: $sidebar-color;
padding: 0 2rem 0.5rem 2rem;
padding: 0.25rem 2rem 0.5rem 2rem;
margin-bottom: 0.75rem;
display: flex;
justify-content: flex-end;