Giter Site home page Giter Site logo

azure-cosmos-java-sql-api-samples's Introduction

page_type languages products description urlFragment
sample
java
java sdk
Sample code repo for Azure Cosmos DB Java SDK for SQL API

Azure Cosmos DB Java SQL API Samples

Sample code repo for Azure Cosmos DB Java SDK for SQL API. By cloning and running these samples, and then studying their implementations, you will have an example for sending various requests to Azure Cosmos DB from Java SDK via the SQL API.

Contents

File/folder Description
src Java sample source code. Many samples have 'sync' and 'async' variants
.gitignore Define what to ignore at commit time.
CHANGELOG.md List of changes to the sample.
CONTRIBUTING.md Guidelines for contributing to the sample.
README.md This README file.
LICENSE The license for the sample.
pom.xml Maven Project Object Model File

Prerequisites

  • Maven
  • Java SE JRE 8
  • Setting up an Azure Cosmos DB account through the Azure Portal. The Create a database account section of this guide walks you through account creation.
  • The hostname and master key for your Azure Cosmos DB account

Setup

Clone the sample to your PC. Using your Java IDE, open pom.xml as a Maven project.

Running the sample

These environment variables must be set

ACCOUNT_HOST=your account hostname;ACCOUNT_KEY=your account master key

in order to give the samples read/write access to your account.

To run a sample, specify its Main Class

com.azure.cosmos.examples.sample.synchronicity.MainClass

where sample.synchronicity.MainClass can be

  • crudquickstart.sync.SampleCRUDQuickstart
  • crudquickstart.async.SampleCRUDQuickstartAsync
  • indexmanagement.sync.SampleIndexManagement
  • indexmanagement.async.SampleIndexManagementAsync
  • storedprocedure.sync.SampleStoredProcedure
  • storedprocedure.async.SampleStoredProcedureAsync
  • changefeed.SampleChangeFeedProcessor (Changefeed has only an async sample, no sync sample.)

Build and execute from command line without an IDE: From top-level directory of repo:

mvn clean package
mvn exec:java -Dexec.mainClass="com.azure.cosmos.examples.sample.synchronicity.MainClass" -DACCOUNT_HOST=your account hostname -DACCOUNT_KEY=your account master key

where sample.synchronicity.MainClass, your account hostname, and your account master key are to be filled in as above. This will rebuild and run the selected sample.

Key concepts

These samples cover a range of Azure Cosmos DB usage topics from more to less basic:

  • Basic management of databases, containers and items
  • Indexing, stored procedures
  • Change Feed

Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com.

When you submit a pull request, a CLA bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

azure-cosmos-java-sql-api-samples's People

Contributors

abhirockzz avatar anfeldma-ms avatar deepub avatar fabianmeiswinkel avatar jcocchi avatar kushagrathapar avatar microsoft-github-operations[bot] avatar microsoftopensource avatar moderakh avatar ravitella avatar rinatmini avatar snehagunda avatar srinikhilreddy avatar theovankraay avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

azure-cosmos-java-sql-api-samples's Issues

setPostTriggerInclude doesn't set context response?

Hi,

I'm trying to use setPostTriggerInclude to run a post-trigger after a document added. However, I'm getting null from context.getResponse()

Post-trigger javascript (myPostTrigger):

function myPostTrigger() {
  var context = getContext();
  var container = context.getCollection();
  var response = context.getResponse(); // item that was created

  var createdItem = response.getBody();

  // we are hitting this check
  if(!createdItem) throw new Error("No created item from hooked action.")
}

Java

        JsonNode jsonNode = new ObjectMapper().valueToTree(item);
        //  Create item using container
        List<String> postTriggers = new ArrayList<>();
        postTriggers.add("myPostTrigger");
        CosmosItemRequestOptions cosmosItemRequestOptions = new CosmosItemRequestOptions()
                .setPostTriggerInclude(postTriggers);
        logger.info("itemInJson : " + jsonNode.toString());
        CosmosItemResponse<JsonNode> response = cosmosDbContainer.getContainer().createItem(jsonNode, cosmosItemRequestOptions);

I can confirm that the createItem creates document properly without the postTrigger set.

ChangeFeedProcessorBuilder.handleAllVersionsAndDeletesChanges doesn't received any messages

I created a junit with the code from https://github.com/Azure-Samples/azure-cosmos-java-sql-api-samples/blob/fb3cee8e3d8faa69d97f6a61d4bf0633992426d0/src/main/java/com/azure/cosmos/examples/changefeed/SampleChangeFeedProcessorForAllVersionsAndDeletesMode.java

but when I run it with Cosmos DB emulator, I don't received messages with ChangeFeedProcessor and handleAllVersionsAndDeletesChanges.

I'm using the latest docker image version for the emulator : mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator:latest

I created a project to reproduce the issue.

I have few tests

src/test/java/com/example/demoredis/CosmosDBTests.java (with .handleChanges and it works)
src/test/java/com/example/demoredis/CosmosDBFeed3Tests.java : SampleChangeFeedProcessorForAllVersionsAndDeletesMode (doesn't work)

here the logs for CosmosDBFeed3Tests

[debug.log](https://github.com/Azure/azure-cosmos-db-emulator-docker/files/10297050/debug.log)

here my source code
demo-cosmos-feed-update.zip

CosmosStoredProcedureRequestOptions. setIfMatchETag(eTag) is not working.

if the etag is mismatched, still executes the store proc successfully

`
public void executeStoredProc(Item item) {

CosmosStoredProcedureRequestOptions options = new CosmosStoredProcedureRequestOptions();
options.setIfMatchETag(item.getEtag());
options.setPartitionKey(new PartitionKey(partitionKey));
List<Object> params = Arrays.asList(new ObjectMapper().writeValueAsString(item));
try {
    CosmosStoredProcedureResponse executeResponse = container.getScripts()
            .getStoredProcedure(updateInvstStoredProcId)
            .execute(params, options);
    if (null != executeResponse) {
        return executeResponse.getResponseAsString();
    }
} catch (Exception e) {
    log.error(e);
}

}
`

Bulk operation is not working

` private void bulkCreateItems(List messages) {

    CosmosItemResponse cosmosItemResponse = container.createItem(messages.get(0));

    List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>();
    for (Message message : messages) {
        cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(message, new PartitionKey(message.getEngagementId())));
    }

    
    Iterable<CosmosBulkOperationResponse<Message>> iterable = container.executeBulkOperations(cosmosItemOperations);
    
    }
    `
    
    Note:  CosmosItemResponse cosmosItemResponse = container.createItem(messages.get(0)); 
    is working and able to create the item in cosmos. Which means the container object is fine and working. It fails on the execute bulk operation part.
    
    

    Error:
    
    16:50:39.104 [bulk-executor-bounded-elastic-9] ERROR com.azure.cosmos.implementation.batch.BulkExecutor -- HandleTransactionalBatchOperationResult - Fail, PKRange 0, Response Status Code 200, Operation Status Code -1, ItemOperation[Type: CREATE, PK: ["c8ad54fb-043d-4749-911c-2846bbd8c081"], id: null], Context: BulkExecutor-1[n/a] Thread[Name: bulk-executor-bounded-elastic-9,Group: main, isDaemon: true, Id: 58]

Pagination based on continuation token

We have a requirement for clients to get results in paginated way. Pagination was implemented as below:

final CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();
options.setResponseContinuationTokenLimitInKb(2);
options.setQueryMetricsEnabled(true);
        
// Retrieve the documents response using DocumentClient.
Iterable<FeedResponse<Reservation>> feedResponseIterator = container
                .queryItems(query, options, Reservation.class)
                .iterableByPage(continuationToken, 50);
List<Object> docsList = new ArrayList<>();
ResponseWithHeaders result = new ResponseWithHeaders();
FeedResponse<Reservation> page = feedResponseIterator.iterator().next();
String nextToken = page.getContinuationToken();
docsList.addAll(page.getResults());

Issue:
This is working fine when overall result set is less e.g., 120 documents returned as 3 pages. This is not working fine when overall results set is large. When total no. of documents is ~1000, same continuationToken is being returned causing an endless loop and not able to get documents beyond initial 50 docs returned.

CosmosPagedIterable.byPage is loading multiple pages even if we set page sige

Followed the example given below, CosmosPagedIterable.byPage is loading multiple pages with single query and do while loop is getting executed only once.

String query = "SELECT * FROM Families";

    int pageSize = 100; //No of docs per page
    int currentPageNumber = 1;
    int documentNumber = 0;
    String continuationToken = null;

    double requestCharge = 0.0;

    // First iteration (continuationToken = null): Receive a batch of query response pages
    // Subsequent iterations (continuationToken != null): Receive subsequent batch of query response pages, with continuationToken indicating where the previous iteration left off
    do {
        logger.info("Receiving a set of query response pages.");
        logger.info("Continuation Token: " + continuationToken + "\n");

        CosmosQueryRequestOptions queryOptions = new CosmosQueryRequestOptions();

        Iterable<FeedResponse<Family>> feedResponseIterator =
                container.queryItems(query, queryOptions, Family.class).iterableByPage(continuationToken,pageSize);

        for (FeedResponse<Family> page : feedResponseIterator) {
            logger.info(String.format("Current page number: %d", currentPageNumber));
             // Access all of the documents in this result page
            for (Family docProps : page.getResults()) {
                documentNumber++;
            }

            // Accumulate the request charge of this page
            requestCharge += page.getRequestCharge();

            // Page count so far
            logger.info(String.format("Total documents received so far: %d", documentNumber));

            // Request charge so far
            logger.info(String.format("Total request charge so far: %f\n", requestCharge));

            // Along with page results, get a continuation token
            // which enables the client to "pick up where it left off"
            // in accessing query response pages.
            continuationToken = page.getContinuationToken();

            currentPageNumber++;
        }

    } while (continuationToken != null);

Sql parameter list not working

Hi ,
The below query not working . Its not accepting the list . No results returned.

private SqlQuerySpec getQuery(List namesList) {
ArrayList paramList = new ArrayList();
paramList.add(new SqlParameter("@NAMEs", namesList));
SqlQuerySpec querySpec = new SqlQuerySpec(
"SELECT * FROM Test t WHERE t.name in(@NAMEs)",
paramList);
return querySpec;
}

executeStoredProcedureArrayArg example does not work

I believe the SampleStoredProcedure.executeStoredProcedureArrayArg() method's objective is to demonstrate how to pass arrays as an argument to the stored procedure. However the sproc_args list isn't being inserted into the Cosmos container.
Instead the javascript stored proc is simply creating a hard coded doc without accepting the array.

        sproc_args.add(new CustomPOJO("idA"));
        sproc_args.add(new CustomPOJO("idB"));
        sproc_args.add(new CustomPOJO("idC"));

        CosmosStoredProcedureResponse executeResponse = container.getScripts()
                .getStoredProcedure(sprocId+"ArrayArg")
                .execute(sproc_args, options);

The stored procedure ignores the input parameter array.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.