End-to-end client examples

See complete client examples of how to connect to a database, load data into a collection, and perform a similarity search.

Python client example

Create a file named quickstart.py.

quickstart.py
import os

from astrapy.db import AstraDB

# Initialize the client. The namespace parameter is optional if you use
# "default_keyspace".
db = AstraDB(
    token=os.environ["ASTRA_DB_APPLICATION_TOKEN"],
    api_endpoint=os.environ["ASTRA_DB_API_ENDPOINT"],
    namespace="default_keyspace",
)
print(db)

# Create a collection. The default similarity metric is "cosine".
collection = db.create_collection("vector_test", dimension=5, metric="cosine")
print(collection)

# Insert documents into the collection
documents = [
    {
        "_id": "1",
        "text": "ChatGPT integrated sneakers that talk to you",
        "$vector": [0.1, 0.15, 0.3, 0.12, 0.05],
    },
    {
        "_id": "2",
        "text": "An AI quilt to help you sleep forever",
        "$vector": [0.45, 0.09, 0.01, 0.2, 0.11],
    },
    {
        "_id": "3",
        "text": "A deep learning display that controls your mood",
        "$vector": [0.1, 0.05, 0.08, 0.3, 0.6],
    },
]
res = collection.insert_many(documents)
print(res)

# Perform a similarity search
query = [0.15, 0.1, 0.1, 0.35, 0.55]
results = collection.vector_find(query, limit=2, fields={"text", "$vector"})

for document in results:
    print(document)
    
# Delete the collection
res = db.delete_collection(collection_name="vector_test")
print(res)

TypeScript client example

Create a file named quickstart.ts.

quickstart.ts
import { AstraDB } from "@datastax/astra-db-ts";

async function main() {

  const { ASTRA_DB_APPLICATION_TOKEN, ASTRA_DB_API_ENDPOINT } = process.env;

  // Initialize the client. The keyspace parameter is optional if you use
  // "default_keyspace".
  const db = new AstraDB(
      ASTRA_DB_APPLICATION_TOKEN,
      ASTRA_DB_API_ENDPOINT,
      "default_keyspace"
  );

  // Create a collection. The default similarity metric is "cosine".
  await db.createCollection(
    "vector_test",
    {
      "vector": {
        "dimension": 5,
        "metric": "cosine"
      }
    }
  );
  const collection = await db.collection("vector_test");
  console.log(collection);

  // Insert documents into the collection
  const documents = [
      {
          "_id": "1",
          "text": "ChatGPT integrated sneakers that talk to you",
          "$vector": [0.1, 0.15, 0.3, 0.12, 0.05],
      },
      {
          "_id": "2",
          "text": "An AI quilt to help you sleep forever",
          "$vector": [0.45, 0.09, 0.01, 0.2, 0.11],
      },
      {
          "_id": "3",
          "text": "A deep learning display that controls your mood",
          "$vector": [0.1, 0.05, 0.08, 0.3, 0.6],
      }
  ];
  const results = await collection.insertMany(documents);
  console.log(results);

  // Define the search options
  const options = {
      sort: {
          "$vector": [0.15, 0.1, 0.1, 0.35, 0.55],
      },
      limit: 5
  };

  // Perform a similarity search
  const docs = await collection.find({}, options).toArray();
  docs.forEach(doc => console.log(doc));

  // Delete the collection
  const response = await db.dropCollection("vector_test");
  console.log(response);

}

main().catch(console.error);

Java client example

Create a file named Quickstart.java in the ./src/main/java/com/example/ directory of your project.

src/main/java/com/example/Quickstart.java
package com.example;

import com.dtsx.astra.sdk.AstraDB;
import com.dtsx.astra.sdk.AstraDBCollection;
import io.stargate.sdk.data.domain.JsonDocument;
import io.stargate.sdk.data.domain.JsonDocumentResult;
import io.stargate.sdk.data.domain.SimilarityMetric;
import io.stargate.sdk.data.domain.CollectionDefinition;
import java.util.List;
import java.util.stream.Stream;

public class Quickstart {

  public static void main(String[] args) {
    // Loading Arguments
    String astraToken = System.getenv("ASTRA_DB_APPLICATION_TOKEN");
    String astraApiEndpoint = System.getenv("ASTRA_DB_API_ENDPOINT");

    // Initialize the client. The keyspace parameter is optional if you use
    // "default_keyspace".
    AstraDB db = new AstraDB(astraToken, astraApiEndpoint, "default_keyspace");
    System.out.println("Connected to AstraDB");

    // Create a collection. The default similarity metric is cosine.
    CollectionDefinition colDefinition = CollectionDefinition.builder()
        .name("vector_test")
        .vector(5, SimilarityMetric.cosine)
        .build();
    db.createCollection(colDefinition);
    AstraDBCollection collection = db.collection("vector_test");
    System.out.println("Created a collection");

    // Insert documents into the collection
    collection.insertMany(List.of(
        new JsonDocument()
            .id("1")
            .put("text", "ChatGPT integrated sneakers that talk to you")
            .vector(new float[]{0.1f, 0.15f, 0.3f, 0.12f, 0.05f}),
        new JsonDocument()
            .id("2")
            .put("text", "An AI quilt to help you sleep forever")
            .vector(new float[]{0.45f, 0.09f, 0.01f, 0.2f, 0.11f}),
        new JsonDocument()
            .id("3")
            .put("text", "A deep learning display that controls your mood")
            .vector(new float[]{0.1f, 0.05f, 0.08f, 0.3f, 0.6f})
        ));
    System.out.println("Inserted documents into the collection");

    // Perform a similarity search
    Stream<JsonDocumentResult> resultsSet = collection.findVector(
        new float[]{0.15f, 0.1f, 0.1f, 0.35f, 0.55f},
        10
    );
    resultsSet.forEach(System.out::println);

    // Delete the collection
    db.deleteCollection("vector_test");
    System.out.println("Deleted the collection");

  }
}

Was this helpful?

Give Feedback

How can we improve the documentation?

© 2024 DataStax | Privacy policy | Terms of use

Apache, Apache Cassandra, Cassandra, Apache Tomcat, Tomcat, Apache Lucene, Apache Solr, Apache Hadoop, Hadoop, Apache Pulsar, Pulsar, Apache Spark, Spark, Apache TinkerPop, TinkerPop, Apache Kafka and Kafka are either registered trademarks or trademarks of the Apache Software Foundation or its subsidiaries in Canada, the United States and/or other countries. Kubernetes is the registered trademark of the Linux Foundation.

General Inquiries: +1 (650) 389-6000, info@datastax.com