The Astra DB Client, as the name suggests, is a client library that interacts with the various APIs of the Astra DataStax Platform. It enables users to connect to, utilize, and administer the Astra Vector product. The library encompasses two distinct clients working in tandem:
AstraDBAmin: This class is initialized exclusively using an organization administrator token and enables the creation and deletion of databases via the DevOps API. It facilitates automation and administration within your organization's tenant.
AstraDB: This is the primary endpoint, connecting exclusively to a single database to perform all operations for your applications. It requires initialization with a database administrator token and also necessitates the API endpoint of your database.
AstraDBCollection: This client class facilitates all operations at the collection level, including find(), insert(), and delete(). It is instantiated through the AstraDB class and accommodates operations on both vector and non-vector collections.
AstraDBRepository: This class represents a specialized form of AstraDBCollection designed for use with Java beans (T). It embodies the repository pattern, streamlining the management and access of domain entities.
Use the java reference documentation to install a Java Development Kit (JDK) tailored for your operating system. After installation, you can validate your setup with the following command:
java--version
Install Apache Maven (3.9+) or Gradle
Samples and tutorials are designed to be used with Apache Maven. Follow the instructions in the reference documentation to install Maven. To validate your installation, use the following command:
Once logged into the user interface, select settings from the left menu and then click on the tokens tab to create a new token.
You want to pick the following role:
Properties
Values
Token Role
Organization Administrator
The Token contains properties Client ID, Client Secret and the token. You will only need the third (starting with AstraCS:)
{
"ClientId": "ROkiiDZdvPOvHRSgoZtyAapp",
"ClientSecret": "fakedfaked",
"Token":"AstraCS:fake" <========== use this field
}
To operate with AstraDBAdmin, this specific organization-level token is required. For tasks involving AstraDB at the database level, a database-level token suffices. The procedure for creating such a token is detailed in subsequent sections.
AstraDB class is the entry point of the SDK. It enables interactions with one particular database within your Astra environment. The initialization can be achieved in multiple ways:
Using a token along with the api_endpoint. Both are retrieved from the Astra user interface.
Using a token with the database identifier and eventually the region.
To establish this connection, you can generate a token via the user interface. This token will be assigned the Database Administrator permission level, which grants sufficient privileges for interacting with a specific database.
The api_endpoint is obtained from the user interface. It adheres to the following pattern: https://{database-identifier}-{database-region}.apps.astra.datastax.com.
packagecom.dtsx.astra.sdk.documentation;importcom.dtsx.astra.sdk.AstraDB;importcom.dtsx.astra.sdk.AstraDBCollection;importio.stargate.sdk.data.domain.query.Filter;importio.stargate.sdk.data.domain.JsonDocument;importio.stargate.sdk.data.domain.JsonDocumentResult;importjava.util.Map;importjava.util.stream.Stream;publicclassQuickStart{publicstaticvoidmain(String[]args){// Initialize the clientAstraDBmyDb=newAstraDB("TOKEN","API_ENDPOINT");// Create a collectionAstraDBCollectiondemoCollection=myDb.createCollection("demo",14);// Insert vectorsdemoCollection.insertOne(newJsonDocument().id("doc1")// generated if not set.vector(newfloat[]{1f,0f,1f,1f,1f,1f,0f,0f,0f,0f,0f,0f,0f,0f}).put("product_name","HealthyFresh - Beef raw dog food").put("product_price",12.99));demoCollection.insertOne(newJsonDocument().id("doc2").vector(newfloat[]{1f,1f,1f,1f,1f,0f,0f,0f,0f,0f,0f,0f,0f,0f}).put("product_name","HealthyFresh - Chicken raw dog food").put("product_price",9.99));demoCollection.insertOne(newJsonDocument().id("doc3").vector(newfloat[]{1f,1f,1f,1f,1f,0f,0f,0f,0f,0f,0f,0f,0f,0f}).data(Map.of("product_name","HealthyFresh - Chicken raw dog food")));demoCollection.insertOne(newJsonDocument().id("doc4").vector(newfloat[]{1.0f,1.0f,1.0f,1.0f,1.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.0f}).put("product_name","HealthyFresh - Chicken raw dog food").put("product_price",9.99));// Perform a similarity searchfloat[]embeddings=newfloat[]{1f,1f,1f,1f,1f,0f,0f,0f,0f,0f,0f,0f,0f,0f};FiltermetadataFilter=newFilter().where("product_price").isEqualsTo(9.99);intmaxRecord=10;longtop=System.currentTimeMillis();Stream<JsonDocumentResult>resultsSet=demoCollection.findVector(embeddings,metadataFilter,maxRecord);System.out.println(System.currentTimeMillis()-top);}}
packagecom.dtsx.astra.sdk.documentation;importcom.dtsx.astra.sdk.AstraDB;importjava.util.UUID;publicclassConnecting{publicstaticvoidmain(String[]args){// Default initializationAstraDBdb=newAstraDB("TOKEN","API_ENDPOINT");// Initialize with a non-default keyspaceAstraDBdb1=newAstraDB("TOKEN","API_ENDPOINT","<keyspace>");// Initialize with an identifier instead of an endpointUUIDdatabaseUuid=UUID.fromString("<database_id>");AstraDBdb2=newAstraDB("TOKEN",databaseUuid);}}
AstraDB is a vector database that manages multiple collections. Each collection (AstraDBCollection) is identified by a name and stores schema-less documents. It is capable of holding any JSON document, each uniquely identified by an _id. Additionally, a JSON document within AstraDB can contain a vector. It is important to note that all documents within the same collection should utilize vectors of the same type, characterized by consistent dimensions and metrics.
packagecom.dtsx.astra.sdk.documentation;importcom.dtsx.astra.sdk.AstraDB;importcom.dtsx.astra.sdk.AstraDBCollection;importio.stargate.sdk.data.domain.CollectionDefinition;importio.stargate.sdk.data.domain.SimilarityMetric;importio.stargate.sdk.data.exception.DataApiException;publicclassCreateCollection{publicstaticvoidmain(String[]args){AstraDBdb=newAstraDB("TOKEN","API_ENDPOINT");// Create a non-vector collectionAstraDBCollectioncollection1=db.createCollection("collection_simple");// Create a vector collectionAstraDBCollectioncollection2=db.createCollection("collection_vector1",14,SimilarityMetric.cosine);// Create a vector collection with a builderAstraDBCollectioncollection3=db.createCollection(CollectionDefinition.builder().name("collection_vector2").vector(1536,SimilarityMetric.euclidean).build());// Collection names should use snake case ([a-zA-Z][a-zA-Z0-9_]*)try{db.createCollection("invalid.name");}catch(DataApiExceptione){// invalid.name is not valid}}}
packagecom.dtsx.astra.sdk.documentation;importcom.dtsx.astra.sdk.AstraDB;importio.stargate.sdk.data.domain.CollectionDefinition;publicclassFindAllCollections{publicstaticvoidmain(String[]args){AstraDBdb=newAstraDB("TOKEN","API_ENDPOINT");// Get Collection Namesdb.findAllCollectionsNames().forEach(System.out::println);// Iterate over all collections and print each vector definitiondb.findAllCollections().forEach(col->{System.out.print("\nname="+col.getName());if(col.getOptions()!=null&&col.getOptions().getVector()!=null){CollectionDefinition.Options.Vectorvector=col.getOptions().getVector();System.out.print(", dim="+vector.getDimension());System.out.print(", metric="+vector.getMetric());}});}}
packagecom.dtsx.astra.sdk.documentation;importcom.dtsx.astra.sdk.AstraDB;importio.stargate.sdk.data.domain.CollectionDefinition;importjava.util.Optional;publicclassFindCollection{publicstaticvoidmain(String[]args){AstraDBdb=newAstraDB("TOKEN","API_ENDPOINT");// Find a collectionOptional<CollectionDefinition>collection=db.findCollectionByName("collection_vector1");// Check if a collection existsbooleancollectionExists=db.isCollectionExists("collection_vector2");}}
packagecom.dtsx.astra.sdk.documentation;importcom.dtsx.astra.sdk.AstraDB;publicclassDeleteCollection{publicstaticvoidmain(String[]args){AstraDBdb=newAstraDB("TOKEN","API_ENDPOINT");// Delete an existing collectiondb.deleteCollection("collection_vector2");}}
packagecom.dtsx.astra.sdk.documentation;importcom.dtsx.astra.sdk.AstraDB;importcom.dtsx.astra.sdk.AstraDBCollection;importio.stargate.sdk.data.domain.JsonDocumentMutationResult;importio.stargate.sdk.data.domain.JsonDocument;importjava.util.Map;publicclassInsertOne{publicstaticvoidmain(String[]args){AstraDBdb=newAstraDB("TOKEN","API_ENDPOINT");// Assumes a collection with a vector field of dimension 14AstraDBCollectioncollection=db.getCollection("collection_vector1");// You must delete any existing rows with the same IDs as the// rows you want to insertcollection.deleteAll();// Insert rows defined by key/valuecollection.insertOne(newJsonDocument().id("doc1")// uuid is generated if not explicitely set.vector(newfloat[]{1f,0f,1f,1f,1f,1f,0f,0f,0f,0f,0f,0f,0f,0f}).put("product_name","HealthyFresh - Beef raw dog food").put("product_price",12.99));// Insert rows defined as a JSON Stringcollection.insertOne(newJsonDocument().data("{"+"\"_id\": \"doc2\", "+"\"$vector\": [1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], "+"\"product_name\": \"HealthyFresh - Chicken raw dog food\", "+"\"product_price\": 9.99"+"}"));// Insert rows defined as a Map Asynchronouslycollection.insertOneASync(newJsonDocument().id("doc3").vector(newfloat[]{1f,1f,1f,1f,1f,0f,0f,0f,0f,0f,0f,0f,0f,0f}).data(Map.of("product_name","HealthyFresh - Chicken raw dog food")));// If you do not provide an ID, they are generated automaticallyJsonDocumentMutationResultresult=collection.insertOne(newJsonDocument().put("demo",1));StringgeneratedId=result.getDocument().getId();}}
Data API Payload
{"insertOne":{"document":{"product_name":"HealthyFresh - Chicken raw dog food","product_price":9.99,"_id":"f2472946-cc9f-4ad1-801d-f1cf21d8cb38","$vector":[0.3,0.3,0.3,0.3,0.3,0.3,0.3,0.3,0.3,0.3,0.3,0.3,0.3,0.3]}}}
packagecom.dtsx.astra.sdk.documentation;importcom.dtsx.astra.sdk.AstraDB;importcom.dtsx.astra.sdk.AstraDBCollection;importio.stargate.sdk.data.domain.JsonDocument;importio.stargate.sdk.data.domain.JsonDocumentMutationResult;importorg.junit.jupiter.api.Assertions;import staticio.stargate.sdk.data.domain.DocumentMutationStatus.CREATED;import staticio.stargate.sdk.data.domain.DocumentMutationStatus.UNCHANGED;import staticio.stargate.sdk.data.domain.DocumentMutationStatus.UPDATED;publicclassUpsertOne{publicstaticvoidmain(String[]args){AstraDBdb=newAstraDB("TOKEN","API_ENDPOINT");// Assumes a collection with a vector field of dimension 14AstraDBCollectioncollection=db.getCollection("collection_vector1");// Insert rows defined by key/valueJsonDocumentdoc1=newJsonDocument().id("doc1")// uuid is generated if not explicitely set.put("product_name","HealthyFresh - Beef raw dog food").put("product_price",12.99);// Create the documentJsonDocumentMutationResultres1=collection.upsertOne(doc1);Assertions.assertEquals(CREATED,res1.getStatus());// Nothing happenedJsonDocumentMutationResultres2=collection.upsertOne(doc1);Assertions.assertEquals(UNCHANGED,res1.getStatus());// Document is updated (async)doc1.put("new_property","value");collection.upsertOneASync(doc1).thenAccept(res->Assertions.assertEquals(UPDATED,res.getStatus()));}}
The underlying REST API is paged. The maximum page size is 20.
To perform bulk loading, distribution of the workload is recommended
insertMany**Chunked** are a helper to distribute the workload
If more than 20 documents are provided chunking is applied under the hood
Signatures
// Use a json StringList<JsonDocumentMutationResult>insertMany(Stringjson);CompletableFuture<List<JsonDocumentMutationResult>>insertManyASync(Stringjson);// Use an Array of JsonDocumentsList<JsonDocumentMutationResult>insertMany(JsonDocument...documents);CompletableFuture<List<JsonDocumentMutationResult>>insertManyASync(JsonDocument...documents);// Use a list of JsonDocumentList<JsonDocumentMutationResult>insertManyJsonDocuments(List<JsonDocument>documents);CompletableFuture<List<JsonDocumentMutationResult>>insertManyJsonDocumentsASync(List<JsonDocument>documents);// Use an Array of Document<T>List<DocumentMutationResult<DOC>>insertMany(Document<DOC>...documents);CompletableFuture<List<DocumentMutationResult<DOC>>>insertManyASync(Document<DOC>...documents);// Use a list of Document<T>List<DocumentMutationResult<DOC>>insertMany(List<Document<DOC>>documents);CompletableFuture<List<DocumentMutationResult<DOC>>>insertManyASync(List<Document<DOC>>documents);
packagecom.dtsx.astra.sdk.documentation;importcom.dtsx.astra.sdk.AstraDB;importcom.dtsx.astra.sdk.AstraDBCollection;importio.stargate.sdk.data.domain.JsonDocumentMutationResult;importio.stargate.sdk.data.domain.JsonDocument;importjava.util.List;importjava.util.stream.Collectors;importjava.util.stream.IntStream;publicclassInsertMany{publicstaticvoidmain(String[]args){AstraDBdb=newAstraDB("TOKEN","API_ENDPOINT");AstraDBCollectioncollection=db.createCollection("collection_vector1",14);// Insert documents into the collection (IDs are generated automatically)List<JsonDocumentMutationResult>identifiers=collection.insertManyJsonDocuments(List.of(newJsonDocument().vector(newfloat[]{1f,0f,1f,1f,.5f,1f,0f,0.3f,0f,0f,0f,0f,0f,0f}).put("product_name","Yet another product").put("product_price",99.99),newJsonDocument().vector(newfloat[]{1f,0f,1f,1f,.5f,1f,0f,0.3f,0f,0f,0f,0f,0f,0f}).put("product_name","product3").put("product_price",99.99)));// Insert large collection of documentsList<JsonDocument>largeList=IntStream.rangeClosed(1,1000).mapToObj(id->newJsonDocument().id(String.valueOf(id)).put("sampleKey",id)).collect(Collectors.toList());intchunkSize=20;// In between 1 and 20intthreadCount=10;// How many chunks processed in parallelList<JsonDocumentMutationResult>result=collection.insertManyChunkedJsonDocuments(largeList,chunkSize,threadCount);}}
// Insert a list of json documentsList<JsonDocumentMutationResult>insertManyChunkedJsonDocuments(List<JsonDocument>documents,intchunkSize,intconcurrency);CompletableFuture<List<JsonDocumentMutationResult>>insertManyChunkedJsonDocumentsAsync(List<JsonDocument>documents,intchunkSize,intconcurrency);// Insert a list of documentsList<DocumentMutationResult<DOC>>insertManyChunked(List<Document<DOC>>documents,intchunkSize,intconcurrency);CompletableFuture<List<DocumentMutationResult<DOC>>>insertManyChunkedASync(List<Document<DOC>>documents,intchunkSize,intconcurrency);
// Use a json StringList<JsonDocumentMutationResult>upsertMany(Stringjson);CompletableFuture<List<JsonDocumentMutationResult>>upsertManyASync(Stringjson);// Use a list of JsonDocumentList<JsonDocumentMutationResult>upsertManyJsonDocuments(List<JsonDocument>documents);CompletableFuture<List<JsonDocumentMutationResult>>upsertManyJsonDocumentsASync(List<JsonDocument>documents);// Use a list of Document<T>List<DocumentMutationResult<DOC>>upsertMany(List<Document<DOC>>documents);CompletableFuture<List<DocumentMutationResult<DOC>>>upsertManyASync(List<Document<DOC>>documents);
packagecom.dtsx.astra.sdk.documentation;importcom.dtsx.astra.sdk.AstraDB;importcom.dtsx.astra.sdk.AstraDBCollection;importcom.fasterxml.jackson.annotation.JsonProperty;importio.stargate.sdk.data.domain.JsonDocumentResult;importio.stargate.sdk.data.domain.odm.DocumentResult;importjava.util.Optional;publicclassFindById{publicstaticvoidmain(String[]args){AstraDBdb=newAstraDB("TOKEN","API_ENDPOINT");AstraDBCollectioncollection=db.getCollection("collection_vector1");// Fetch a document by ID and return it as JSONOptional<JsonDocumentResult>res=collection.findById("doc1");res.ifPresent(jsonResult->System.out.println(jsonResult.getSimilarity()));// Fetch a document by ID and map it to an object with ResultMapperOptional<DocumentResult<MyBean>>res2=collection.findById("doc1",record->{MyBeanbean=newMyBean((String)record.getData().get("product_name"),(Double)record.getData().get("product_price"));returnnewDocumentResult<>(record,bean);});// Fetch a document by ID and map it to a classOptional<DocumentResult<MyBean>>res3=collection.findById("doc1",MyBean.class);// Check if a document existsbooleanexists=collection.isDocumentExists("doc1");}publicstaticclassMyBean{@JsonProperty("product_name")Stringname;@JsonProperty("product_price")Doubleprice;publicMyBean(Stringname,Doubleprice){this.name=name;this.price=price;}}}
packagecom.dtsx.astra.sdk.documentation;importcom.dtsx.astra.sdk.AstraDB;importcom.dtsx.astra.sdk.AstraDBCollection;importcom.fasterxml.jackson.annotation.JsonProperty;importio.stargate.sdk.data.domain.odm.DocumentResult;importjava.util.Optional;publicclassFindByVector{publicstaticvoidmain(String[]args){AstraDBdb=newAstraDB("TOKEN","API_ENDPOINT");AstraDBCollectioncollection=db.getCollection("collection_vector1");// Fetch a row by vector and return JSONcollection.findOneByVector(newfloat[]{1f,0f,1f,1f,1f,1f,0f,0f,0f,0f,0f,0f,0f,0f}).ifPresent(jsonResult->System.out.println(jsonResult.getSimilarity()));// Fetch a row by ID and map it to an object with ResultMapperOptional<DocumentResult<MyBean>>res2=collection.findOneByVector(newfloat[]{1f,0f,1f,1f,1f,1f,0f,0f,0f,0f,0f,0f,0f,0f},record->{MyBeanbean=newMyBean((String)record.getData().get("product_name"),(Double)record.getData().get("product_price"));returnnewDocumentResult<>(record,bean);});// Fetch a row by ID and map the result to a classOptional<DocumentResult<MyBean>>res3=collection.findOneByVector(newfloat[]{1f,0f,1f,1f,1f,1f,0f,0f,0f,0f,0f,0f,0f,0f},MyBean.class);}publicstaticclassMyBean{@JsonProperty("product_name")Stringname;@JsonProperty("product_price")Doubleprice;publicMyBean(Stringname,Doubleprice){this.name=name;this.price=price;}}}
Under the hood every search against the REST Api is done by providing 4 parameters:
$filter: which are your criteria (where clause)
$projection: which list the fields you want to retrieve (select)
$sort: which order the results in memory (order by) or the vector search (order by ANN)
$options: that will contains all information like paging, limit, etc.
The SelectQuery class is a builder that will help you to build the query. It is a fluent API that will help you to build the query.
As for findById and findByVector there are 3 methods available to retrieve a document. If the SelectQuery has multiple
matches objects only the first will be returned. In doubt use find() or even better findPage() not to exhaust all the
collection.
packagecom.dtsx.astra.sdk.documentation;importcom.dtsx.astra.sdk.AstraDB;importcom.dtsx.astra.sdk.AstraDBCollection;importio.stargate.sdk.data.domain.query.Filter;importio.stargate.sdk.data.domain.query.SelectQuery;import staticio.stargate.sdk.http.domain.FilterOperator.EQUALS_TO;publicclassFindOne{publicstaticvoidmain(String[]args){AstraDBdb=newAstraDB("TOKEN","API_ENDPOINT");AstraDBCollectioncollection=db.createCollection("collection_vector1",14);// Retrieve the first document where product_price existsFilterfilter=newFilter().where("product_price").exists();collection.findOne(SelectQuery.builder().filter(filter).build()).ifPresent(System.out::println);// Retrieve the first document where product_price is 12.99Filterfilter2=newFilter().where("product_price").isEqualsTo(12.99);collection.findOne(SelectQuery.builder().filter(filter2).build()).ifPresent(System.out::println);// Send the request as a JSON Stringcollection.findOne("{"+"\"filter\":{"+"\"product_price\":9.99,"+"\"product_name\":\"HealthyFresh - Chicken raw dog food\"}"+"}").ifPresent(System.out::println);// Only retrieve the product_name and product_price fieldscollection.findOne(SelectQuery.builder().select("product_name","product_price").filter(filter2).build()).ifPresent(System.out::println);// Perform a similarity searchcollection.findOne(SelectQuery.builder().filter(filter2).orderByAnn(newfloat[]{1f,0f,1f,1f,1f,1f,0f,0f,0f,0f,0f,0f,0f,0f}).build());// Perform a complex query with AND and ORSelectQuerysq2=newSelectQuery();FilteryaFilter=newFilter().and().or().where("product_price",EQUALS_TO,9.99).where("product_name",EQUALS_TO,"HealthyFresh - Beef raw dog food").end().or().where("product_price",EQUALS_TO,9.99).where("product_name",EQUALS_TO,"HealthyFresh - Beef raw dog food").end();collection.findOne(sq2).ifPresent(System.out::println);}}
With the Json API all queries are paged. The maximum page size is 20. The method findAll() and find() will fetch the
pages one after the other until pagingState is null. Use those functions with caution.
To retrieve every document of a collection use findAll()
// Find All for VectorStore<MyBean>Stream<JsonResult>all=col1.findAll();
packagecom.dtsx.astra.sdk.documentation;importcom.dtsx.astra.sdk.AstraDB;importcom.dtsx.astra.sdk.AstraDBCollection;importio.stargate.sdk.data.domain.query.Filter;importio.stargate.sdk.data.domain.query.SelectQuery;importjava.util.ArrayList;importjava.util.HashMap;importjava.util.List;importjava.util.Map;publicclassFind{publicstaticvoidmain(String[]args){AstraDBdb=newAstraDB("TOKEN","API_ENDPOINT");AstraDBCollectioncollection=db.createCollection("collection_vector1",14);// Retrieve the first document with a product_priceFilterfilter=newFilter().where("product_price").exists();collection.find(SelectQuery.builder().filter(filter).build()).forEach(System.out::println);// Retrieve the first document where the product_price is 12.99Filterfilter2=newFilter().where("product_price").isEqualsTo(12.99);collection.find(SelectQuery.builder().filter(filter2).build()).forEach(System.out::println);// Only retrieve the product_name and product_price fieldscollection.find(SelectQuery.builder().select("product_name","product_price").filter(filter2).build()).forEach(System.out::println);// Order the results by similaritycollection.find(SelectQuery.builder().filter(filter2).orderByAnn(newfloat[]{1f,0f,1f,1f,1f,1f,0f,0f,0f,0f,0f,0f,0f,0f}).build()).forEach(System.out::println);// Order the results by a specific fieldFilterfilter3=newFilter().where("product_name").isEqualsTo("HealthyFresh - Chicken raw dog food");collection.find(SelectQuery.builder().filter(filter3).orderBy("product_price",1).build()).forEach(System.out::println);// Complex query with AND and OR:// (product_price == 9.99 OR product_name == "HealthyFresh - Beef raw dog food")// AND (product_price == 12.99 OR product_name == "HealthyFresh - Beef raw dog food")SelectQuerysq2=newSelectQuery();sq2.setFilter(newHashMap<>());Map<String,List<Map<String,Object>>>or1Criteria=newHashMap<>();or1Criteria.put("$or",newArrayList<Map<String,Object>>());or1Criteria.get("$or").add(Map.of("product_price",9.99));or1Criteria.get("$or").add(Map.of("product_name","HealthyFresh - Beef raw dog food"));Map<String,List<Map<String,Object>>>or2Criteria=newHashMap<>();or2Criteria.put("$or",newArrayList<Map<String,Object>>());or2Criteria.get("$or").add(Map.of("product_price",12.99));or2Criteria.get("$or").add(Map.of("product_name","HealthyFresh - Beef raw dog food"));List<Map<String,List<Map<String,Object>>>>andCriteria=newArrayList<>();andCriteria.add(or1Criteria);andCriteria.add(or2Criteria);sq2.getFilter().put("$and",andCriteria);collection.find(sq2).forEach(System.out::println);}}
packagecom.dtsx.astra.sdk.documentation;importcom.dtsx.astra.sdk.AstraDB;importcom.dtsx.astra.sdk.AstraDBCollection;importio.stargate.sdk.data.domain.JsonDocumentResult;importio.stargate.sdk.data.domain.query.Filter;importio.stargate.sdk.data.domain.query.SelectQuery;importjava.util.stream.Stream;publicclassFindVector{publicstaticvoidmain(String[]args){AstraDBdb=newAstraDB("TOKEN","API_ENDPOINT");AstraDBCollectioncollection=db.createCollection("collection_vector1",14);float[]embeddings=newfloat[]{1f,0f,1f,1f,1f,1f,0f,0f,0f,0f,0f,0f,0f,0f};FiltermetadataFilter=newFilter().where("product_price").isEqualsTo(9.99);intmaxRecord=10;// Retrieve all document with product price based on the ann searchcollection.findVector(SelectQuery.builder().filter(metadataFilter).orderByAnn(embeddings).withLimit(maxRecord).build()).forEach(System.out::println);// Same using another signatureStream<JsonDocumentResult>result=collection.findVector(embeddings,metadataFilter,maxRecord);}}
Every request is paged with the Json API and the maximum page size is 20. The methods return Page that contains the data but also a field called `pagingState
Find Page
The signature are close to the find(). Reason is that find() is using findPage under the hood. The difference is that it will exhaust all the pages
and return a Stream<JsonResult>.
packagecom.dtsx.astra.sdk.documentation;importcom.dtsx.astra.sdk.AstraDB;importcom.dtsx.astra.sdk.AstraDBCollection;importcom.fasterxml.jackson.annotation.JsonProperty;importio.stargate.sdk.core.domain.Page;importio.stargate.sdk.data.domain.JsonDocumentResult;importio.stargate.sdk.data.domain.odm.DocumentResult;importio.stargate.sdk.data.domain.query.Filter;importio.stargate.sdk.data.domain.query.SelectQuery;publicclassFindPage{publicstaticvoidmain(String[]args){AstraDBdb=newAstraDB("TOKEN","API_ENDPOINT");AstraDBCollectioncollection=db.createCollection("collection_vector1",14);// Retrieve page 1 of a search (up to 20 results)Filterfilter=newFilter().where("product_price").exists();Page<JsonDocumentResult>page1=collection.findPage(SelectQuery.builder().filter(filter).build());// Retrieve page 2 of the same search (if there are more than 20 results)Filterfilter2=newFilter().where("product_price").isEqualsTo(12.99);page1.getPageState().ifPresent(pageState->{Page<JsonDocumentResult>page2=collection.findPage(SelectQuery.builder().filter(filter2).withPagingState(pageState).build());});// You can map the output as Result<T> using either a Java pojo or mapperPage<DocumentResult<MyBean>>page=collection.findPage(SelectQuery.builder().filter(filter2).build(),MyBean.class);}publicstaticclassMyBean{@JsonProperty("product_name")Stringname;@JsonProperty("product_price")Doubleprice;publicMyBean(Stringname,Doubleprice){this.name=name;this.price=price;}}}
packagecom.dtsx.astra.sdk.documentation;importcom.dtsx.astra.sdk.AstraDB;importcom.dtsx.astra.sdk.AstraDBCollection;importio.stargate.sdk.data.domain.JsonDocument;importio.stargate.sdk.data.domain.query.UpdateQuery;import staticio.stargate.sdk.http.domain.FilterOperator.EQUALS_TO;publicclassUpdateOne{publicstaticvoidmain(String[]args){AstraDBdb=newAstraDB("TOKEN","API_ENDPOINT");AstraDBCollectioncollection=db.getCollection("collection_vector1");// You must delete any existing rows with the same IDs as the// rows you want to insertcollection.deleteAll();// Upsert a document based on a querycollection.updateOne(UpdateQuery.builder().updateSet("product_name",12.99).where("product_name",EQUALS_TO,"HealthyFresh - Beef raw dog food").build());// Upsert a document by IDcollection.upsertOne(newJsonDocument().id("id1").put("product_name",12.99));}}
packagecom.dtsx.astra.sdk.documentation;importcom.dtsx.astra.sdk.AstraDB;importcom.dtsx.astra.sdk.AstraDBCollection;importio.stargate.sdk.data.domain.query.Filter;importio.stargate.sdk.data.domain.query.UpdateQuery;importio.stargate.sdk.http.domain.FilterOperator;publicclassUpdateMany{publicstaticvoidmain(String[]args){AstraDBdb=newAstraDB("TOKEN","API_ENDPOINT");AstraDBCollectioncollection=db.getCollection("collection_vector1");// Update multiple documents based on a querycollection.updateMany(UpdateQuery.builder().updateSet("product_name",12.99).filter(newFilter("product_name",FilterOperator.EQUALS_TO,"HealthyFresh - Beef raw dog food")).build());}}
packagecom.dtsx.astra.sdk.documentation;importcom.dtsx.astra.sdk.AstraDB;importcom.dtsx.astra.sdk.AstraDBCollection;importio.stargate.sdk.data.domain.query.DeleteQuery;importio.stargate.sdk.data.domain.query.DeleteResult;publicclassDeleteOne{publicstaticvoidmain(String[]args){AstraDBdb=newAstraDB("TOKEN","API_ENDPOINT");AstraDBCollectioncollection=db.createCollection("collection_vector1",14);// Delete items from an existing collection with a queryDeleteResultdeletedCount=collection.deleteOne(DeleteQuery.deleteById("id1"));}}
packagecom.dtsx.astra.sdk.documentation;importcom.dtsx.astra.sdk.AstraDB;importcom.dtsx.astra.sdk.AstraDBCollection;importio.stargate.sdk.data.domain.query.DeleteQuery;importio.stargate.sdk.data.domain.query.DeleteResult;import staticio.stargate.sdk.http.domain.FilterOperator.EQUALS_TO;publicclassDeleteMany{publicstaticvoidmain(String[]args){AstraDBdb=newAstraDB("TOKEN","API_ENDPOINT");AstraDBCollectioncollection=db.createCollection("collection_vector1",14);// Build our queryDeleteQuerydeleteQuery=DeleteQuery.builder().where("product_price",EQUALS_TO,9.99).build();// Deleting only up to 20 recordDeleteResultpage=collection.deleteManyPaged(deleteQuery);// Deleting all documents matching queryDeleteResultallDeleted=collection.deleteMany(deleteQuery);// Deleting all documents matching query in distributed wayDeleteResultresult=collection.deleteManyChunked(deleteQuery,5);}}
packagecom.dtsx.astra.sdk.documentation;importcom.dtsx.astra.sdk.AstraDB;importcom.dtsx.astra.sdk.AstraDBCollection;publicclassClearCollection{publicstaticvoidmain(String[]args){AstraDBdb=newAstraDB("TOKEN","API_ENDPOINT");AstraDBCollectioncollection=db.createCollection("collection_vector1",14);// Delete all rows from an existing collectioncollection.deleteAll();}}
Instead of interacting with the database with key/values you may want to
associate an object to each record in the collection for this you can use CollectionRepository. If we reproduce the sample before
Instead of working with raw JsonDocument you can work with your own object. The object will be serialized to JSON and stored in the database. You do not want to provide a ResultMapper each time but rather use the repository pattern.
We will follow the signature of the CrudRepository from Spring Data.
packagecom.dtsx.astra.sdk.documentation;importcom.dtsx.astra.sdk.AstraDB;importcom.dtsx.astra.sdk.AstraDBRepository;importcom.fasterxml.jackson.annotation.JsonProperty;importio.stargate.sdk.data.domain.CollectionDefinition;importio.stargate.sdk.data.domain.SimilarityMetric;publicclassObjectMappingCreateCollection{staticclassProduct{@JsonProperty("product_name")privateStringname;@JsonProperty("product_price")privateDoubleprice;}publicstaticvoidmain(String[]args){AstraDBdb=newAstraDB("TOKEN","API_ENDPOINT");// Create a non-vector collectionAstraDBRepository<Product>collection1=db.createCollection("collection_simple",Product.class);// Create a vector collection with a builderAstraDBRepository<Product>collection2=db.createCollection(CollectionDefinition.builder().name("collection_vector2").vector(1536,SimilarityMetric.euclidean).build(),Product.class);}}
packagecom.dtsx.astra.sdk.documentation;importcom.dtsx.astra.sdk.AstraDB;importcom.dtsx.astra.sdk.AstraDBRepository;importcom.fasterxml.jackson.annotation.JsonProperty;importio.stargate.sdk.data.domain.DocumentMutationResult;importio.stargate.sdk.data.domain.odm.Document;importjava.util.List;publicclassObjectMappingInsertMany{staticclassProduct{@JsonProperty("product_name")privateStringname;@JsonProperty("product_price")privateDoubleprice;Product(Stringname,Doubleprice){this.name=name;this.price=price;}}publicstaticvoidmain(String[]args){AstraDBdb=newAstraDB("TOKEN","API_ENDPOINT");AstraDBRepository<Product>productRepository=db.createCollection("collection_vector1",14,Product.class);// Insert documents into the collection (IDs are generated automatically)List<DocumentMutationResult<Product>>identifiers=productRepository.saveAll(List.of(newDocument<Product>().vector(newfloat[]{1f,0f,1f,1f,.5f,1f,0f,0.3f,0f,0f,0f,0f,0f,0f}).data(newProduct("product1",9.99)),newDocument<Product>().vector(newfloat[]{1f,0f,1f,1f,.5f,1f,0f,0.3f,0f,0f,0f,0f,0f,0f}).data(newProduct("product2",12.99))));}}
packagecom.dtsx.astra.sdk.documentation;importcom.dtsx.astra.sdk.AstraDB;importcom.dtsx.astra.sdk.AstraDBRepository;importcom.fasterxml.jackson.annotation.JsonProperty;importio.stargate.sdk.data.domain.odm.DocumentResult;importjava.util.Optional;publicclassObjectMappingFindOne{staticclassProduct{@JsonProperty("product_name")privateStringname;@JsonProperty("product_price")privateDoubleprice;}publicstaticvoidmain(String[]args){AstraDBdb=newAstraDB("TOKEN","API_ENDPOINT");AstraDBRepository<Product>productRepository=db.createCollection("collection_vector1",14,Product.class);// Retrieve a products from its idOptional<DocumentResult<Product>>res1=productRepository.findById("id1");// Retrieve a product from its vectorfloat[]vector=newfloat[]{1f,0f,1f,1f,1f,1f,0f,0f,0f,0f,0f,0f,0f,0f};Optional<DocumentResult<Product>>res2=productRepository.findByVector(vector);}}
packagecom.dtsx.astra.sdk.documentation;importcom.dtsx.astra.sdk.AstraDB;importcom.dtsx.astra.sdk.AstraDBCollection;importio.stargate.sdk.data.domain.query.Filter;importio.stargate.sdk.data.domain.query.SelectQuery;importjava.util.ArrayList;importjava.util.HashMap;importjava.util.List;importjava.util.Map;publicclassObjectMappingFind{publicstaticvoidmain(String[]args){AstraDBdb=newAstraDB("TOKEN","API_ENDPOINT");AstraDBCollectioncollection=db.createCollection("collection_vector1",14);// Retrieve the first document with a product_priceFilterfilter=newFilter().where("product_price").exists();collection.find(SelectQuery.builder().filter(filter).build()).forEach(System.out::println);// Retrieve the first document where product_price is 12.99Filterfilter2=newFilter().where("product_price").isEqualsTo(12.99);collection.find(SelectQuery.builder().filter(filter2).build()).forEach(System.out::println);// Only retrieve the product_name and product_price fieldscollection.find(SelectQuery.builder().select("product_name","product_price").filter(filter2).build()).forEach(System.out::println);// Order the results by similaritycollection.find(SelectQuery.builder().filter(filter2).orderByAnn(newfloat[]{1f,0f,1f,1f,1f,1f,0f,0f,0f,0f,0f,0f,0f,0f}).build()).forEach(System.out::println);// Order the results by a specific fieldcollection.find(SelectQuery.builder().filter(filter2).orderBy("product_price",1).build()).forEach(System.out::println);// Complex query with AND and OR:// (product_price == 9.99 OR product_name == "HealthyFresh - Beef raw dog food")// AND (product_price == 12.99 OR product_name == "HealthyFresh - Beef raw dog food")SelectQuerysq2=newSelectQuery();sq2.setFilter(newHashMap<>());Map<String,List<Map<String,Object>>>or1Criteria=newHashMap<>();or1Criteria.put("$or",newArrayList<Map<String,Object>>());or1Criteria.get("$or").add(Map.of("product_price",9.99));or1Criteria.get("$or").add(Map.of("product_name","HealthyFresh - Beef raw dog food"));Map<String,List<Map<String,Object>>>or2Criteria=newHashMap<>();or2Criteria.put("$or",newArrayList<Map<String,Object>>());or2Criteria.get("$or").add(Map.of("product_price",12.99));or2Criteria.get("$or").add(Map.of("product_name","HealthyFresh - Beef raw dog food"));List<Map<String,List<Map<String,Object>>>>andCriteria=newArrayList<>();andCriteria.add(or1Criteria);andCriteria.add(or2Criteria);sq2.getFilter().put("$and",andCriteria);collection.find(sq2).forEach(System.out::println);}}
packagecom.dtsx.astra.sdk.documentation;importcom.dtsx.astra.sdk.AstraDB;importcom.dtsx.astra.sdk.AstraDBRepository;importcom.fasterxml.jackson.annotation.JsonProperty;importio.stargate.sdk.data.domain.odm.DocumentResult;importio.stargate.sdk.data.domain.query.Filter;importjava.util.List;publicclassObjectMappingFindVector{staticclassProduct{@JsonProperty("product_name")privateStringname;@JsonProperty("product_price")privateDoubleprice;}publicstaticvoidmain(String[]args){AstraDBdb=newAstraDB("TOKEN","API_ENDPOINT");AstraDBRepository<Product>productRepository=db.createCollection("collection_vector1",14,Product.class);// Perform a semantic searchfloat[]embeddings=newfloat[]{1f,0f,1f,1f,1f,1f,0f,0f,0f,0f,0f,0f,0f,0f};FiltermetadataFilter=newFilter().where("product_price").isEqualsTo(9.99);intmaxRecord=10;List<DocumentResult<Product>>res=productRepository.findVector(embeddings,metadataFilter,maxRecord);// If you do not have max record or metadata filter, you can use the followingproductRepository.findVector(embeddings,maxRecord);productRepository.findVector(embeddings,metadataFilter);}}
packagecom.dtsx.astra.sdk.documentation;importcom.dtsx.astra.sdk.AstraDB;importcom.dtsx.astra.sdk.AstraDBRepository;importcom.fasterxml.jackson.annotation.JsonProperty;importio.stargate.sdk.data.domain.odm.Document;publicclassObjectMappingUpdateOne{staticclassProduct{@JsonProperty("product_name")privateStringname;@JsonProperty("product_price")privateDoubleprice;Product(Stringname,Doubleprice){this.name=name;this.price=price;}}publicstaticvoidmain(String[]args){AstraDBdb=newAstraDB("TOKEN","API_ENDPOINT");AstraDBRepository<Product>productRepository=db.createCollection("collection_vector1",14,Product.class);// Upsert a documentproductRepository.save(newDocument<Product>().id("product1").vector(newfloat[]{1f,0f,1f,1f,.5f,1f,0f,0.3f,0f,0f,0f,0f,0f,0f}).data(newProduct("product1",9.99)));}}
packagecom.dtsx.astra.sdk.documentation;importcom.dtsx.astra.sdk.AstraDB;importcom.dtsx.astra.sdk.AstraDBRepository;importcom.fasterxml.jackson.annotation.JsonProperty;importio.stargate.sdk.data.domain.DocumentMutationResult;importio.stargate.sdk.data.domain.odm.Document;importjava.util.List;publicclassObjectMappingUpdateMany{staticclassProduct{@JsonProperty("product_name")privateStringname;@JsonProperty("product_price")privateDoubleprice;Product(Stringname,Doubleprice){this.name=name;this.price=price;}}publicstaticvoidmain(String[]args){AstraDBdb=newAstraDB("TOKEN","API_ENDPOINT");AstraDBRepository<Product>productRepository=db.createCollection("collection_vector1",14,Product.class);// Insert documents into the collection (IDs are generated automatically)List<DocumentMutationResult<Product>>identifiers=productRepository.saveAll(List.of(newDocument<Product>().vector(newfloat[]{1f,0f,1f,1f,.5f,1f,0f,0.3f,0f,0f,0f,0f,0f,0f}).data(newProduct("product1",9.99)),newDocument<Product>().vector(newfloat[]{1f,0f,1f,1f,.5f,1f,0f,0.3f,0f,0f,0f,0f,0f,0f}).data(newProduct("product2",12.99))));}}
packagecom.dtsx.astra.sdk.documentation;importcom.dtsx.astra.sdk.AstraDB;importcom.dtsx.astra.sdk.AstraDBRepository;importcom.fasterxml.jackson.annotation.JsonProperty;importio.stargate.sdk.data.domain.odm.Document;publicclassObjectMappingDeleteOne{staticclassProduct{@JsonProperty("product_name")privateStringname;@JsonProperty("product_price")privateDoubleprice;}publicstaticvoidmain(String[]args){AstraDBdb=newAstraDB("TOKEN","API_ENDPOINT");AstraDBRepository<Product>collection1=db.createCollection("collection_simple",Product.class);// Delete a document by IDcollection1.deleteById("id1");// Delete a specific documentcollection1.delete(newDocument<Product>().id("id2"));}}
packagecom.dtsx.astra.sdk.documentation;importcom.dtsx.astra.sdk.AstraDB;importcom.dtsx.astra.sdk.AstraDBRepository;importcom.fasterxml.jackson.annotation.JsonProperty;importio.stargate.sdk.data.domain.query.DeleteQuery;importio.stargate.sdk.data.domain.query.DeleteResult;import staticio.stargate.sdk.http.domain.FilterOperator.EQUALS_TO;publicclassObjectMappingDeleteMany{staticclassProduct{@JsonProperty("product_name")privateStringname;@JsonProperty("product_price")privateDoubleprice;}publicstaticvoidmain(String[]args){AstraDBdb=newAstraDB("TOKEN","API_ENDPOINT");// Create a vector collectionAstraDBRepository<Product>collection1=db.createCollection("collection_simple",Product.class);// Delete rows based on a queryDeleteQueryq=DeleteQuery.builder().where("product_price",EQUALS_TO,9.99).build();DeleteResultres=collection1.deleteAll(q);}}
packagecom.dtsx.astra.sdk.documentation;importcom.dtsx.astra.sdk.AstraDB;importcom.dtsx.astra.sdk.AstraDBRepository;importcom.fasterxml.jackson.annotation.JsonProperty;publicclassObjectMappingClearCollection{staticclassProduct{@JsonProperty("product_name")privateStringname;@JsonProperty("product_price")privateDoubleprice;}publicstaticvoidmain(String[]args){AstraDBdb=newAstraDB("TOKEN","API_ENDPOINT");AstraDBRepository<Product>collection1=db.createCollection("collection_simple",Product.class);// Delete all rows in a collectioncollection1.deleteAll();}}
To work with Databases you need to use a token with organization level permissions. You will work with the class AstraDBClient
To establish a connection with AstraDB using the client SDK, you are required to supply a token. This token enables two primary connection modes:
Direct database-level connection, facilitating access to a specific database. It is the one decribe above and primay way of working with the SDK.
Organization-level connection, which allows interaction with multiple databases under your organization. This is what we will detailed now
AstraDBClient class is used to facilitate interactions with all components within your Astra organization, rather than limiting operations to a single database.
This approach enables a broader scope of management and control across the organization's databases. The token used for this connection must be scoped to the organization with
packagecom.dtsx.astra.sdk.documentation;importcom.dtsx.astra.sdk.AstraDBAdmin;publicclassConnectingAdmin{publicstaticvoidmain(String[]args){// Default InitializationAstraDBAdminclient=newAstraDBAdmin("TOKEN");// You can omit the token if you defined the `ASTRA_DB_APPLICATION_TOKEN`// environment variable or if you are using the Astra CLI.AstraDBAdmindefaultClient=newAstraDBAdmin();}}
packagecom.dtsx.astra.sdk.documentation;importcom.dtsx.astra.sdk.AstraDBAdmin;importcom.dtsx.astra.sdk.db.domain.Database;importjava.util.stream.Stream;publicclassFindAllDatabases{publicstaticvoidmain(String[]args){AstraDBAdminclient=newAstraDBAdmin("TOKEN");booleanexists=client.isDatabaseExists("<database_name>");// List all available databasesStream<Database>dbStream=client.listDatabases();}}
packagecom.dtsx.astra.sdk.documentation;importcom.dtsx.astra.sdk.AstraDBAdmin;importcom.dtsx.astra.sdk.db.domain.CloudProviderType;importjava.util.UUID;publicclassCreateDatabase{publicstaticvoidmain(String[]args){AstraDBAdminclient=newAstraDBAdmin("TOKEN");// Choose a cloud provider (GCP, AZURE, AWS) and a regionCloudProviderTypecloudProvider=CloudProviderType.GCP;StringcloudRegion="us-east1";// Create a databaseUUIDnewDbId=client.createDatabase("<database_name>",cloudProvider,cloudRegion);}}
packagecom.dtsx.astra.sdk.documentation;importcom.dtsx.astra.sdk.AstraDBAdmin;importcom.dtsx.astra.sdk.db.domain.Database;importjava.util.Optional;importjava.util.UUID;importjava.util.stream.Stream;publicclassFindDatabase{publicstaticvoidmain(String[]args){AstraDBAdminclient=newAstraDBAdmin("TOKEN");// Check if a database existsbooleanexists=client.isDatabaseExists("<database_name>");// Find a database by name (names may not be unique)Stream<Database>dbStream=client.getDatabaseInformations("<database_name>");Optional<Database>dbByName=dbStream.findFirst();// Find a database by IDOptional<Database>dbById=client.getDatabaseInformations(UUID.fromString("<replace_with_db_uuid>"));}}
packagecom.dtsx.astra.sdk.documentation;importcom.dtsx.astra.sdk.AstraDBAdmin;importjava.util.UUID;publicclassDeleteDatabase{publicstaticvoidmain(String[]args){AstraDBAdminclient=newAstraDBAdmin("TOKEN");// Delete an existing databaseclient.dropDatabase("<database_name>");// Delete an existing database by IDclient.dropDatabase(UUID.fromString("<replace_with_db_uuid>"));}}
packagecom.dtsx.astra.sdk.documentation;importcom.dtsx.astra.sdk.AstraDBAdmin;publicclassCreateKeyspace{publicstaticvoidmain(String[]args){AstraDBAdminclient=newAstraDBAdmin("TOKEN");// Create a Keyspaceclient.createKeyspace("<db_name>","<keyspace_name>");}}
packagecom.dtsx.astra.sdk.documentation;importcom.dtsx.astra.sdk.AstraDBAdmin;publicclassDeleteKeyspace{publicstaticvoidmain(String[]args){AstraDBAdminclient=newAstraDBAdmin("TOKEN");// Create a Keyspaceclient.deleteKeyspace("<db_name>","<keyspace_name>");}}
packagecom.dtsx.astra.sdk.documentation;importcom.dtsx.astra.sdk.AstraDBAdmin;publicclassDeleteKeyspace{publicstaticvoidmain(String[]args){AstraDBAdminclient=newAstraDBAdmin("TOKEN");// Create a Keyspaceclient.deleteKeyspace("<db_name>","<keyspace_name>");}}
Cassio is framework originally implement in Python to use Open Source Cassandra as a Vector Store.
It has been partially ported in Java. Idea is java to use the same table created by CassIO.
packagecom.dtsx.astra.sdk.documentation;importcom.datastax.oss.driver.api.core.CqlSession;importcom.dtsx.astra.sdk.AstraDBAdmin;importcom.dtsx.astra.sdk.cassio.CassIO;importcom.dtsx.astra.sdk.utils.TestUtils;importjava.util.UUID;publicclassCassIOConnection{publicstaticvoidmain(String[]args){// Create db if not existsUUIDdatabaseId=newAstraDBAdmin("TOKEN").createDatabase("database");// Initializing CqlSessiontry(CqlSessioncqlSession=CassIO.init("TOKEN",databaseId,TestUtils.TEST_REGION,AstraDBAdmin.DEFAULT_KEYSPACE)){cqlSession.execute("SELECT datacenter FROM system.local;").one().get("datacenter",String.class);}}}
packagecom.dtsx.astra.sdk.documentation;importcom.datastax.oss.driver.api.core.CqlSession;importcom.dtsx.astra.sdk.AstraDBAdmin;importcom.dtsx.astra.sdk.cassio.AnnQuery;importcom.dtsx.astra.sdk.cassio.CassIO;importcom.dtsx.astra.sdk.cassio.MetadataVectorRecord;importcom.dtsx.astra.sdk.cassio.MetadataVectorTable;importcom.dtsx.astra.sdk.utils.TestUtils;importjava.util.List;importjava.util.Map;importjava.util.UUID;publicclassCassIOMetadataVectorTable{publicstaticvoidmain(String[]args){// Create db if not existsUUIDdatabaseId=newAstraDBAdmin("TOKEN").createDatabase("database");// Initializing CqlSessiontry(CqlSessioncqlSession=CassIO.init("TOKEN",databaseId,TestUtils.TEST_REGION,AstraDBAdmin.DEFAULT_KEYSPACE)){// Initializing table with the dimensionMetadataVectorTablevector_Store=CassIO.metadataVectorTable("vector_store",1536);vector_Store.create();// Insert VectorsStringpartitionId=UUID.randomUUID().toString();MetadataVectorRecordrecord=newMetadataVectorRecord();record.setVector(List.of(0.1f,0.2f,0.3f,0.4f));record.setMetadata(Map.of("key","value"));record.setBody("Sample text fragment");record.setAttributes("handy field for special attributes");vector_Store.put(record);// Semantic SearchAnnQueryquery=AnnQuery.builder().embeddings(List.of(0.1f,0.2f,0.3f,0.4f)).metaData(Map.of("key","value")).build();vector_Store.similaritySearch(query).forEach(result->{System.out.println("Similarity : "+result.getSimilarity());System.out.println("Record : "+result.getEmbedded().getBody());});}}}
packagecom.dtsx.astra.sdk.documentation;importcom.datastax.oss.driver.api.core.CqlSession;importcom.dtsx.astra.sdk.AstraDBAdmin;importcom.dtsx.astra.sdk.cassio.AnnQuery;importcom.dtsx.astra.sdk.cassio.CassIO;importcom.dtsx.astra.sdk.cassio.ClusteredMetadataVectorRecord;importcom.dtsx.astra.sdk.cassio.ClusteredMetadataVectorTable;importcom.dtsx.astra.sdk.utils.TestUtils;importjava.util.List;importjava.util.Map;importjava.util.UUID;import staticcom.dtsx.astra.sdk.cassio.AbstractCassandraTable.PARTITION_ID;publicclassCassIOClusteredMetadataVectorTable{publicstaticvoidmain(String[]args){// Create db if not existsUUIDdatabaseId=newAstraDBAdmin("TOKEN").createDatabase("database");// Initializing CqlSessiontry(CqlSessioncqlSession=CassIO.init("TOKEN",databaseId,TestUtils.TEST_REGION,AstraDBAdmin.DEFAULT_KEYSPACE)){// Initializing table with the dimensionClusteredMetadataVectorTablevector_Store=CassIO.clusteredMetadataVectorTable("vector_store",1536);vector_Store.create();// Insert VectorsStringpartitionId=UUID.randomUUID().toString();ClusteredMetadataVectorRecordrecord=newClusteredMetadataVectorRecord();record.setVector(List.of(0.1f,0.2f,0.3f,0.4f));record.setMetadata(Map.of("key","value"));record.setPartitionId(partitionId);record.setBody("Sample text fragment");record.setAttributes("handy field for special attributes");vector_Store.put(record);// Semantic SearchAnnQueryquery=AnnQuery.builder().embeddings(List.of(0.1f,0.2f,0.3f,0.4f)).metaData(Map.of(PARTITION_ID,partitionId)).build();vector_Store.similaritySearch(query).forEach(result->{System.out.println("Similarity : "+result.getSimilarity());System.out.println("Record : "+result.getEmbedded().getBody());});}}}