Skip to content

Commit e096c2c

Browse files
committed
Update doc
1 parent 0f0289a commit e096c2c

25 files changed

+590
-219
lines changed

README.MD

Lines changed: 112 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,5 +3,115 @@
33

44
`astra-db-java` is the java libraries use to interact with Astra, the Data API with vector support.
55

6-
- `astra-db-ts` is the equivalent in typescript
7-
- `astrapy` is the equivalent in python
6+
- `astra-db-ts` is the equivalent for typescript
7+
- `astrapy` is the equivalent in python
8+
9+
This library is under development and not yet available in Maven Central. You can build it locally and install it in your local repository.
10+
11+
## 1. Local Installation
12+
13+
### 1.1 Prerequisites
14+
15+
#### 📦 Java Development Kit (JDK) 8
16+
- Use the [reference documentation](https://docs.oracle.com/javase/8/docs/technotes/guides/install/install_overview.html) to install a **Java Development Kit**
17+
- Validate your installation with
18+
19+
```bash
20+
java --version
21+
```
22+
23+
#### 📦 Apache Maven
24+
- Use the [reference documentation](https://maven.apache.org/install.html) to install **Apache Maven**
25+
- Validate your installation with
26+
27+
```bash
28+
mvn -version
29+
```
30+
31+
#### 📦 Docker (local Installation)
32+
33+
Docker is an open-source project that automates the deployment of software applications inside containers by providing an additional layer of abstraction and automation of OS-level virtualization on Linux.
34+
35+
### 1.2 Packaging
36+
37+
- Clone the repository
38+
39+
```console
40+
git clone [email protected]:datastax/astra-db-java.git
41+
```
42+
43+
- Build the project (java 11 and Maven is required)
44+
45+
> Note: You should skip the tests if you want to speed up the build, to run the test you need to have a bit of setup:
46+
> - An environment variable `ASTRA_DB_APPLICATION_TOKEN` with your an Organization Administrator Astra token (PROD)
47+
> - An environment variable `ASTRA_DB_APPLICATION_TOKEN_DEV` with your an Organization Administrator Astra token (DEV)
48+
> - A running Data API locally with docker (see the `docker-compose.yml` in the root of the project)
49+
50+
```console
51+
mvn clean install -DskipTests=true
52+
```
53+
54+
### 1.3 Installation
55+
56+
Add the following dependency to your `pom.xml` file:
57+
58+
```xml
59+
60+
<dependency>
61+
<groupId>com.datastax.astra</groupId>
62+
<artifactId>astra-db-java</artifactId>
63+
<version>1.0.0-SNAPSHOT</version>
64+
</dependency>
65+
```
66+
67+
## 2. QuickStart
68+
69+
After creating a new java Project and adding the dependency to your `pom.xml` file, you can start using the library.
70+
71+
Here is a sample class that demonstrates how to use the library:
72+
73+
```java
74+
import com.datastax.astra.client.DataAPIClient;
75+
import com.datastax.astra.client.Collection;
76+
import com.datastax.astra.client.Database;
77+
import com.datastax.astra.client.model.Document;
78+
import com.datastax.astra.client.model.FindIterable;
79+
import java.util.List;
80+
import static com.datastax.astra.client.model.Filters.eq;
81+
import static com.datastax.astra.client.model.SimilarityMetric.cosine;
82+
83+
public class GettingStarted {
84+
public static void main(String[] args) {
85+
// Initializing client with a token
86+
DataAPIClient client = new DataAPIClient("my_token");
87+
88+
// Accessing the Database through the HTTP endpoint
89+
Database db = client.getDatabase("http://db-region.apps.astra.datastax.com");
90+
91+
// Create collection with vector support
92+
Collection<Document> col = db.createCollection("demo", 2, cosine);
93+
94+
// Insert records
95+
col.insertMany(List.of(
96+
new Document("doc1").vector(new float[]{.1f, 0.2f}).append("key", "value1"),
97+
new Document().id("doc2").vector(new float[]{.2f, 0.4f}).append("hello", "world"),
98+
new Document("doc3").vector(new float[]{.5f, 0.6f}).append("key", "value1"))
99+
);
100+
101+
// Search
102+
FindIterable<Document> docs = col.find(
103+
eq("key", "value1"), // metadata filter
104+
new float[] {.5f, .5f}, //vector
105+
10); // maxRecord
106+
107+
// Iterate and print your results
108+
for (Document doc : docs) System.out.println(doc);
109+
}
110+
}
111+
```
112+
113+
### 3. What's Next
114+
115+
- For more information use the [JAVADOC documentation](https://datastaxdevs.github.io/astra-db-java/latest/)
116+
117+
- The `examples` directory contains more examples on how to use the library.

astra-db-java/src/main/java/com/datastax/astra/client/Collection.java

Lines changed: 82 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -45,9 +45,7 @@
4545
import com.datastax.astra.client.model.InsertManyResult;
4646
import com.datastax.astra.client.model.InsertOneResult;
4747
import com.datastax.astra.client.model.Page;
48-
import com.datastax.astra.client.model.Projection;
4948
import com.datastax.astra.client.model.ReplaceOneOptions;
50-
import com.datastax.astra.client.model.SortOrder;
5149
import com.datastax.astra.client.model.Update;
5250
import com.datastax.astra.client.model.UpdateOneOptions;
5351
import com.datastax.astra.client.model.UpdateResult;
@@ -58,10 +56,8 @@
5856
import lombok.Getter;
5957
import lombok.extern.slf4j.Slf4j;
6058

61-
import javax.print.Doc;
6259
import java.util.ArrayList;
6360
import java.util.List;
64-
import java.util.Map;
6561
import java.util.Optional;
6662
import java.util.concurrent.Callable;
6763
import java.util.concurrent.CompletableFuture;
@@ -851,10 +847,10 @@ public Optional<DOC> findOne(Filter filter) {
851847
* // Assuming a Document in the collection with an id field
852848
* Document doc = new Document().id(1).append("name", "John Doe");
853849
* // To find the document with the id 1
854-
* FindOneOptions options = FindOneOptions.builder()
855-
* .withIncludeSimilarity() // return similarity in vector search
856-
* .withProjection(Map.of("name", 1), // return a subset of fields
857-
* .build());
850+
* FindOneOptions options2 = FindOneOptions.builder()
851+
* .withIncludeSimilarity() // return similarity in vector search
852+
* .projections("_id", "name") // return a subset of fields
853+
* .build();
858854
* Optional<Document> foundDoc = collection.findOne(Filters.eq("_id", 1), );
859855
* foundDoc.ifPresent(System.out::println);
860856
* }
@@ -902,6 +898,46 @@ public Optional<DOC> findOne(Filter filter, FindOneOptions options) {
902898
public CompletableFuture<Optional<DOC>> findOneASync(Filter filter) {
903899
return CompletableFuture.supplyAsync(() -> findOne(filter));
904900
}
901+
902+
903+
/**
904+
* Asynchronously attempts to find a single document within the collection that matches the given filter criteria,
905+
* utilizing the specified {@link FindOneOptions} for the query. This method offers a non-blocking approach to
906+
* querying the database, making it well-suited for applications requiring efficient I/O operations without
907+
* compromising the responsiveness of the application.
908+
*
909+
* <p>By executing the search operation in an asynchronous manner, this method allows other tasks to proceed
910+
* concurrently, effectively utilizing system resources and improving application throughput. The query leverages
911+
* a {@link Filter} instance to define the search criteria, and {@link FindOneOptions} to specify query
912+
* customizations, such as projection or sort parameters.</p>
913+
*
914+
* <p>In cases where no document matches the filter, the method returns a {@link CompletableFuture} completed with
915+
* an empty {@link java.util.Optional}, thus avoiding exceptions for non-existent documents. This behavior ensures
916+
* a more graceful handling of such scenarios, allowing for cleaner and more robust client code by leveraging
917+
* the {@link java.util.Optional} pattern within asynchronous workflows.</p>
918+
*
919+
* @param filter The {@link Filter} instance encapsulating the criteria used to identify the desired document.
920+
* It defines the conditions that a document must meet to be considered a match.
921+
* @param options The {@link FindOneOptions} providing additional query configurations such as projection
922+
* and sort criteria to tailor the search operation.
923+
* @return A {@link CompletableFuture<Optional<DOC>>} that, upon completion, contains an {@link Optional<DOC>}
924+
* with the found document if one exists matching the filter criteria. If no matching document is found,
925+
* a completed future with an empty {@link Optional} is returned, facilitating safe asynchronous retrieval.
926+
*
927+
* <p>Example usage:</p>
928+
* <pre>
929+
* {@code
930+
* Filter filter = Filters.eq("id", 1);
931+
* FindOneOptions options = FindOneOptions.builder().projection("name");
932+
* CompletableFuture<Optional<Document>> futureDoc = collection.findOneASync(filter, options);
933+
* futureDoc.thenAccept(doc -> doc.ifPresent(System.out::println));
934+
* }
935+
* </pre>
936+
*/
937+
public CompletableFuture<Optional<DOC>> findOneASync(Filter filter, FindOneOptions options) {
938+
return CompletableFuture.supplyAsync(() -> findOne(filter, options));
939+
}
940+
905941
/**
906942
* Retrieves a document by its identifier from the collection.
907943
* <p>
@@ -918,6 +954,40 @@ public Optional<DOC> findById(Object id) {
918954
return findOne(Filters.eq(id));
919955
}
920956

957+
/**
958+
* Asynchronously retrieves a document from the collection by its unique identifier. This method wraps
959+
* the synchronous {@code findById} operation in a {@link CompletableFuture}, enabling non-blocking
960+
* database queries that improve application responsiveness and efficiency. The method is ideal for
961+
* applications that require the retrieval of specific documents without impacting the performance
962+
* of the user interface or other concurrent operations.
963+
*
964+
* <p>The unique identifier used to locate the document is typically the primary key or a unique field
965+
* within the collection. This method abstracts the complexity of asynchronous programming, providing
966+
* a straightforward way to execute and handle database queries within a non-blocking model.</p>
967+
*
968+
* <p>If the document with the specified identifier exists, it is wrapped in an {@link Optional} and
969+
* returned within the completed future. Otherwise, the future is completed with an empty {@link Optional},
970+
* neatly handling cases where no matching document is found without throwing exceptions.</p>
971+
*
972+
* @param id The unique identifier of the document to retrieve. This can be of any type that the database
973+
* recognizes as a valid identifier format (e.g., String, Integer).
974+
* @return A {@link CompletableFuture<Optional<DOC>>} that, upon completion, contains an {@link Optional<DOC>}
975+
* with the document if found. If no document matches the specified identifier, a completed future
976+
* with an empty {@link Optional} is returned.
977+
*
978+
* <p>Example usage:</p>
979+
* <pre>
980+
* {@code
981+
* Object documentId = "uniqueDocumentId123";
982+
* CompletableFuture<Optional<Document>> futureDocument = collection.findByIdASync(documentId);
983+
* futureDocument.thenAccept(document -> document.ifPresent(System.out::println));
984+
* }
985+
* </pre>
986+
*/
987+
public CompletableFuture<Optional<DOC>> findByIdASync(Object id) {
988+
return CompletableFuture.supplyAsync(() -> findById(id));
989+
}
990+
921991
/**
922992
* Finds all documents in the collection.
923993
*
@@ -942,7 +1012,7 @@ public FindIterable<DOC> find(Filter filter, FindOptions options) {
9421012
* @return A {@link FindIterable} for iterating over all documents in the collection.
9431013
*/
9441014
public FindIterable<DOC> find() {
945-
return find(null, new FindOptions());
1015+
return find(null, FindOptions.builder().build());
9461016
}
9471017

9481018
/**
@@ -956,7 +1026,7 @@ public FindIterable<DOC> find() {
9561026
* @return A {@link FindIterable} for iterating over the documents that match the filter.
9571027
*/
9581028
public FindIterable<DOC> find(Filter filter) {
959-
return find(filter, new FindOptions());
1029+
return find(filter, FindOptions.builder().build());
9601030
}
9611031

9621032
/**
@@ -975,7 +1045,7 @@ public FindIterable<DOC> find(Filter filter) {
9751045
*/
9761046
public FindIterable<DOC> find(Filter filter, float[] vector, int limit) {
9771047
return find(filter, FindOptions.builder()
978-
.withVector(vector)
1048+
.vector(vector)
9791049
.limit(limit)
9801050
.build());
9811051
}
@@ -994,7 +1064,7 @@ public FindIterable<DOC> find(Filter filter, float[] vector, int limit) {
9941064
*/
9951065
public FindIterable<DOC> find(Filter filter, String vectorize, int limit) {
9961066
return find(filter, FindOptions.builder()
997-
.withVectorize(vectorize)
1067+
.vectorize(vectorize)
9981068
.limit(limit)
9991069
.build());
10001070
}

astra-db-java/src/main/java/com/datastax/astra/client/DataAPIClient.java

Lines changed: 3 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -337,31 +337,16 @@ public Database getDatabase(UUID databaseId, String namespace) {
337337
* operations such as querying, updating, and managing data within the specified database and namespace.
338338
*
339339
* @param databaseId The unique identifier of the database to interact with.
340-
* @param cloud The cloud provider on which the database is deployed, values are AWS, GCP, or AZURE.
340+
* @param namespace The namespace associated to this database
341341
* @param region The cloud provider region where the database is deployed.
342-
* @return
343-
* A {@link Database} client configured to interact with the specified database and namespace, allowing for
344-
* data manipulation and query operations.
345-
*/
346-
public Database getDatabase(UUID databaseId, CloudProviderType cloud, String region) {
347-
return getDatabase(databaseId, cloud, region, DEFAULT_NAMESPACE);
348-
}
349-
350-
/**
351-
* Retrieves a client for a specific database, enabling interactions with the Data API. This method allows for
352-
* operations such as querying, updating, and managing data within the specified database and namespace.
353342
*
354-
* @param databaseId The unique identifier of the database to interact with.
355-
* @param cloud The cloud provider on which the database is deployed, values are AWS, GCP, or AZURE.
356-
* @param region The cloud provider region where the database is deployed.
357-
* @param namespace The namespace associated to this database
358343
* @return
359344
* A {@link Database} client configured to interact with the specified database and namespace, allowing for
360345
* data manipulation and query operations.
361346
*/
362-
public Database getDatabase(UUID databaseId, CloudProviderType cloud, String region, String namespace) {
347+
public Database getDatabase(UUID databaseId, String namespace, String region) {
363348
Assert.notNull(databaseId, "databaseId");
364-
Assert.notNull(cloud, "cloud");
349+
Assert.hasLength(namespace, "namespace");
365350
Assert.hasLength(region, "namespace");
366351
return new Database(new AstraApiEndpoint(databaseId, region,
367352
getAstraEnvironment()).getApiEndPoint(),

0 commit comments

Comments
 (0)