Monday, 6 December 2021

Spring Data: ArangoTemplate update multiple documents

ArangoOperations interface provide update method to update multiple documents.

 

Signature

<T> MultiDocumentEntity<? extends DocumentEntity> update(Iterable<T> values, Class<T> entityClass, DocumentUpdateOptions options) throws DataAccessException;

<T> MultiDocumentEntity<? extends DocumentEntity> update(Iterable<T> values, Class<T> entityClass) throws DataAccessException;

 

Partially updates documents, the documents to update are specified by the _key attributes in the objects on values.

 

'DocumentUpdateOptions' is used to add additional options while updating the document. Below table summarizes different properties of DocumentUpdateOptions object.

 

Property

Datatype

Description

keepNull

Boolean

If keepNull is set to false, then this will modify the behaviour of the patch command to remove any attributes from the existing document that are contained in the patch document with an attribute value of null.

mergeObjects

Boolean

Controls whether objects (not arrays) will be merged if present in both the existing and the patch document. If set to false, the value in the patch document will overwrite the existing document's value. If set to true, objects will be merged. The default is true.

waitForSync

Boolean

Wait until document has been synced to disk.

ignoreRevs

Boolean

By default, or if this is set to true, the _rev attributes in the given document is ignored. If this is set to false, then the _rev attribute given in the body document is taken as a precondition. The document is only updated if the current revision is the one specified.

ifMatch

String

ifMatch update a document based on target revision

returnNew

Boolean

Return additionally the complete new document under the attribute new in the result.

returnOld

Boolean

Return additionally the complete previous revision of the changed document under the attribute old in the result.

serializeNull

Boolean

By default, or if this is set to true, all fields of the document which have null values are serialized to VelocyPack otherwise they are excluded from serialization. Use this to update single fields from a stored document.

silent

Boolean

If set to true, an empty object will be returned as response. No meta-data will be returned for the created document. This option can be used to save some network traffic.

streamTransactionId

String

If set, the operation will be executed within the transaction.

 

Example

DocumentUpdateOptions docUpdateOptions = new DocumentUpdateOptions();
docUpdateOptions.returnNew(true);

MultiDocumentEntity<DocumentUpdateEntity> updatedDocs = (MultiDocumentEntity<DocumentUpdateEntity>) arangoTemplate.update(Arrays.asList(emp1ToUpdate, emp2ToUpdate), Employee.class, docUpdateOptions);

Find the below working application.

 

Step 1: Create new maven project ‘arango-template-update-documents’.

 

Step 2: Update pom.xml with maven dependencies.

 

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.sample.app</groupId>
    <artifactId>arango-template-update-documents</artifactId>
    <version>1</version>

    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-parent -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.5</version>
    </parent>


    <dependencies>
        <dependency>
            <groupId>com.arangodb</groupId>
            <artifactId>arangodb-spring-boot-starter</artifactId>
            <version>2.3.3.RELEASE</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Step 3: Define entity class.

 

Employee.java

package com.sample.app.entity;

import com.arangodb.springframework.annotation.ArangoId;
import com.arangodb.springframework.annotation.Document;
import org.springframework.data.annotation.Id;

@Document("employees")
public class Employee {

    @Id // db document field: _key
    private String key;

    @ArangoId // db document field: _id
    private String arangoId;

    private Integer id;
    private String firstName;
    private String lastName;
    private Integer age;

    public Employee(Integer id, String firstName, String lastName) {
        super();
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public Employee() {
        
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getArangoId() {
        return arangoId;
    }

    public void setArangoId(String arangoId) {
        this.arangoId = arangoId;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Employee [key=" + key + ", arangoId=" + arangoId + ", id=" + id + ", firstName=" + firstName
                + ", lastName=" + lastName + ", age=" + age + "]";
    }

}

Step 4: Define Arango DB configuration class.

 

ArangoConfig.java

package com.sample.app.config;

import org.springframework.context.annotation.Configuration;

import com.arangodb.ArangoDB;
import com.arangodb.springframework.annotation.EnableArangoRepositories;
import com.arangodb.springframework.config.ArangoConfiguration;

@Configuration
@EnableArangoRepositories(basePackages = { "com.sample.app" })
public class ArangoConfig implements ArangoConfiguration {

    @Override
    public ArangoDB.Builder arango() {
        return new ArangoDB.Builder().host("localhost", 8529).user("root").password("tiger");
    }

    @Override
    public String database() {
        return "abc_org";
    }
}

Step 5: Define main application class.

 

App.java

package com.sample.app;

import java.util.Arrays;
import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import com.arangodb.entity.DocumentCreateEntity;
import com.arangodb.entity.DocumentUpdateEntity;
import com.arangodb.entity.MultiDocumentEntity;
import com.arangodb.model.DocumentCreateOptions;
import com.arangodb.model.DocumentUpdateOptions;
import com.arangodb.springframework.core.ArangoOperations;
import com.sample.app.entity.Employee;

@SpringBootApplication
public class App {

    @Autowired
    private ArangoOperations arangoTemplate;

    public static void main(String args[]) {
        SpringApplication.run(App.class, args);
    }

    private static void print(DocumentCreateEntity documentCreateEntity) {
        System.out.println("\nid : " + documentCreateEntity.getId());
        System.out.println("key : " + documentCreateEntity.getKey());
        System.out.println("revision : " + documentCreateEntity.getRev());
        System.out.println("doc : " + documentCreateEntity.getNew());
    }

    @Bean
    public CommandLineRunner demo() {

        return (args) -> {
            Employee emp1 = new Employee(1, "Shanmukha Rao", "Kummari");
            Employee emp2 = new Employee(1, "Sarath", "Chandra");

            DocumentCreateOptions docCreateOptions = new DocumentCreateOptions();
            docCreateOptions.returnNew(true);

            DocumentCreateEntity documentCreateEntity1 = (DocumentCreateEntity) arangoTemplate.insert(emp1,
                    docCreateOptions);

            DocumentCreateEntity documentCreateEntity2 = (DocumentCreateEntity) arangoTemplate.insert(emp2,
                    docCreateOptions);

            print(documentCreateEntity1);
            print(documentCreateEntity2);

            Employee emp1ToUpdate = new Employee();
            emp1ToUpdate.setKey(documentCreateEntity1.getKey());
            emp1ToUpdate.setAge(35);

            Employee emp2ToUpdate = new Employee();
            emp2ToUpdate.setKey(documentCreateEntity2.getKey());
            emp2ToUpdate.setAge(42);

            DocumentUpdateOptions docUpdateOptions = new DocumentUpdateOptions();
            docUpdateOptions.returnNew(true);

            MultiDocumentEntity<DocumentUpdateEntity> updatedDocs = (MultiDocumentEntity<DocumentUpdateEntity>) arangoTemplate
                    .update(Arrays.asList(emp1ToUpdate, emp2ToUpdate), Employee.class, docUpdateOptions);

            Collection<DocumentUpdateEntity> updatedDocsCollection = updatedDocs.getDocuments();

            System.out.println("\nDocuments are updated by adding age attribute");
            for (DocumentUpdateEntity updatedDoc : updatedDocsCollection) {
                System.out.println("\nid : " + updatedDoc.getId());
                System.out.println("key : " + updatedDoc.getKey());
                System.out.println("revision : " + updatedDoc.getRev());
                System.out.println("doc : " + updatedDoc.getNew());
            }

        };
    }
}

Total project structure looks like below.



Run App.java, you will see below messages in console.

id : employees/35977
key : 35977
revision : _cUlF23m---
doc : {"_key":"35977","_id":"employees\/35977","_rev":"_cUlF23m---","id":1,"firstName":"Shanmukha Rao","lastName":"Kummari","_class":"com.sample.app.entity.Employee"}

id : employees/35979
key : 35979
revision : _cUlF236---
doc : {"_key":"35979","_id":"employees\/35979","_rev":"_cUlF236---","id":1,"firstName":"Sarath","lastName":"Chandra","_class":"com.sample.app.entity.Employee"}

Documents are updated by adding age attribute

id : employees/35977
key : 35977
revision : _cUlF25C---
doc : {"_key":"35977","_id":"employees\/35977","_rev":"_cUlF25C---","id":1,"firstName":"Shanmukha Rao","lastName":"Kummari","_class":"com.sample.app.entity.Employee","age":35}

id : employees/35979
key : 35979
revision : _cUlF25G---
doc : {"_key":"35979","_id":"employees\/35979","_rev":"_cUlF25G---","id":1,"firstName":"Sarath","lastName":"Chandra","_class":"com.sample.app.entity.Employee","age":42}

You can download complete working application from below link.

https://github.com/harikrishna553/springboot/tree/master/arangodb/arango-template-update-documents


  

Previous                                                    Next                                                    Home

FastAPI: Add validations to request payload

Using Pydantic's Field, you can add validations to the request payload. Let’s see it with an example.

 

Example

class Employee(BaseModel):
    name: str = Field(
        ..., 
        title="Employee name", 
        min_length = 3,
        max_length=30
    )
    
    age : int = Field(..., 
    gt = 18, 
    title="Employee age"
    )

In the above snippet, I added constraints to the fields ‘name’ and ‘age’. ‘name’

 

requestBodyValidations.py

from fastapi import FastAPI, Body
from pydantic import BaseModel, Field
from typing import Optional

app = FastAPI()

# employees information
emps = {
    1 : {
        "name" : "Krishna",
        "age": 32
    }
}

class Employee(BaseModel):
    name: str = Field(
        ..., 
        title="Employee name", 
        min_length = 3,
        max_length=30
    )
    
    age : int = Field(..., 
    gt = 18, 
    title="Employee age"
    )

@app.get("/emps")
def allEmployees():
    return emps

@app.post("/emps")
def createEmployee(emp: Employee):
    noOfEmps = len(emps)
    newId = noOfEmps + 1
    emps[newId] = dict(emp)

    return {
        "id" : newId, 
        "name" : emps[newId]['name'], 
        "age": emps[newId]['age']
        }

Open terminal and execute the command ‘uvicorn requestBodyValidations:app --reload’.

$uvicorn requestBodyValidations:app --reload
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [43421] using statreload
INFO:     Started server process [43423]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

Open the url ‘http://127.0.0.1:8000/docs’ in browser and experiment with swagger documentation.

 

 

Previous                                                    Next                                                    Home

Thursday, 2 December 2021

FastAPI: Singular values in request body

Usually, we can add extra data to an url using query and path parameters. In the same way, we can add extra singular values to the request body using Body() function.

 

Let’s see it with an example.

@app.post("/emps")
def createEmployee(emp: Employee, street: str = Body(...), city: str = Body(...))

 

Above snippet takes a payload like below.

{
  "emp": {
    "name": "Krishna",
    "age": 23
  },
  "street": "sss",
  "city": "Bangalore"
}

 

Find the below working application.

 

requestBodySingularValues.py 

from fastapi import FastAPI, Body
from pydantic import BaseModel
from typing import Optional

app = FastAPI()

# employees information
emps = {
    1 : {
        "name" : "Krishna",
        "age": 32,
        "address": {
            "street" : "Chowdeswari",
            "city" : "Bangalore"
        }
    }
}

class Employee(BaseModel):
    name: str
    age : int

@app.get("/emps")
def allEmployees():
    return emps

@app.post("/emps")
def createEmployee(emp: Employee, street: str = Body(...), city: str = Body(...)):
    noOfEmps = len(emps)
    newId = noOfEmps + 1
    emps[newId] = dict(emp)

    address = {"street" : street, "city" : city}
    emps[newId]['address'] = address

    return {
        "id" : newId, 
        "name" : emps[newId]['name'], 
        "age": emps[newId]['age'],
        "address" : emps[newId]['address']
        }

Open terminal and execute the command ‘uvicorn requestBodySingularValues:app --reload’.

$uvicorn requestBodySingularValues:app --reload
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [38998] using statreload
INFO:     Started server process [39000]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

Open the url ‘http://127.0.0.1:8000/docs’ in browser and experiment with the api 'POST /emps'.



 

 

 

 

 

Previous                                                    Next                                                    Home

Spring data: ArangoTemplate: Update a document

Spring Data ArangoOperations interface provides update method to update the document.

<T> DocumentEntity update(Object id, T value, DocumentUpdateOptions options) throws DataAccessException;
<T> DocumentEntity update(Object id, T value) throws DataAccessException;

 

Partially updates the document identified by document id or key. All attributes from the patch document will be added to the existing document if they do not yet exist, and overwritten in the existing document if they do exist there.

 

'DocumentUpdateOptions' is used to add additional options while updating the document. Below table summarizes different properties of DocumentUpdateOptions object.

 

Property

Datatype

Description

keepNull

Boolean

If keepNull is set to false, then this will modify the behaviour of the patch command to remove any attributes from the existing document that are contained in the patch document with an attribute value of null.

mergeObjects

Boolean

Controls whether objects (not arrays) will be merged if present in both the existing and the patch document. If set to false, the value in the patch document will overwrite the existing document's value. If set to true, objects will be merged. The default is true.

waitForSync

Boolean

Wait until document has been synced to disk.

ignoreRevs

Boolean

By default, or if this is set to true, the _rev attributes in the given document is ignored. If this is set to false, then the _rev attribute given in the body document is taken as a precondition. The document is only updated if the current revision is the one specified.

ifMatch

String

ifMatch update a document based on target revision

returnNew

Boolean

Return additionally the complete new document under the attribute new in the result.

returnOld

Boolean

Return additionally the complete previous revision of the changed document under the attribute old in the result.

serializeNull

Boolean

By default, or if this is set to true, all fields of the document which have null values are serialized to VelocyPack otherwise they are excluded from serialization. Use this to update single fields from a stored document.

silent

Boolean

If set to true, an empty object will be returned as response. No meta-data will be returned for the created document. This option can be used to save some network traffic.

streamTransactionId

String

If set, the operation will be executed within the transaction.

 

Example

 

Map<String, Object> newEmpDoc = new HashMap();
newEmpDoc.put("firstName", "Jaideep");
newEmpDoc.put("age", 35);

DocumentUpdateOptions docUpdateOptions = new DocumentUpdateOptions();
docUpdateOptions.returnNew(true);

DocumentUpdateEntity documentUpdateEntity = (DocumentUpdateEntity) arangoTemplate.update(documentCreateEntity.getId(), newEmpDoc, docUpdateOptions);

 

Follow below step-by-step procedure to build complete working application.

 

Step 1: Create new maven project ‘arango-template-update-document’.

 

Step 2: Update pom.xml with maven dependencies.

 

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.sample.app</groupId>
    <artifactId>arango-template-update-document</artifactId>
    <version>1</version>

    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-parent -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.5</version>
    </parent>


    <dependencies>
        <dependency>
            <groupId>com.arangodb</groupId>
            <artifactId>arangodb-spring-boot-starter</artifactId>
            <version>2.3.3.RELEASE</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

 

Step 3: Define arango db configuration class.

 

ArangoConfig.java

package com.sample.app.config;

import org.springframework.context.annotation.Configuration;

import com.arangodb.ArangoDB;
import com.arangodb.springframework.annotation.EnableArangoRepositories;
import com.arangodb.springframework.config.ArangoConfiguration;

@Configuration
@EnableArangoRepositories(basePackages = { "com.sample.app" })
public class ArangoConfig implements ArangoConfiguration {

    @Override
    public ArangoDB.Builder arango() {
        return new ArangoDB.Builder().host("localhost", 8529).user("root").password("tiger");
    }

    @Override
    public String database() {
        return "abc_org";
    }
}

Step 4: Define main application class.

 

App.java

package com.sample.app;

import java.util.*;
import java.util.Collection;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import com.arangodb.entity.DocumentCreateEntity;
import com.arangodb.entity.DocumentUpdateEntity;
import com.arangodb.entity.MultiDocumentEntity;
import com.arangodb.model.DocumentCreateOptions;
import com.arangodb.model.DocumentUpdateOptions;
import com.arangodb.springframework.core.ArangoOperations;

@SpringBootApplication
public class App {

    @Autowired
    private ArangoOperations arangoTemplate;

    public static void main(String args[]) {
        SpringApplication.run(App.class, args);
    }

    @Bean
    public CommandLineRunner demo() {

        return (args) -> {
            Map<String, Object> empDoc1 = new HashMap();
            empDoc1.put("firstName", "Shanmukha Rao");
            empDoc1.put("lastName", "Kummari");
            empDoc1.put("id", 1);

            DocumentCreateOptions docCreateOptions = new DocumentCreateOptions();
            docCreateOptions.returnNew(true);

            DocumentCreateEntity documentCreateEntity = (DocumentCreateEntity) arangoTemplate.insert(empDoc1,
                    docCreateOptions);

            System.out.println("\nid : " + documentCreateEntity.getId());
            System.out.println("key : " + documentCreateEntity.getKey());
            System.out.println("revision : " + documentCreateEntity.getRev());
            System.out.println("doc : " + documentCreateEntity.getNew());

            // update firstName and add new age property
            Map<String, Object> newEmpDoc = new HashMap();
            newEmpDoc.put("firstName", "Jaideep");
            newEmpDoc.put("age", 35);

DocumentUpdateOptions docUpdateOptions = new DocumentUpdateOptions(); docUpdateOptions.returnNew(true); DocumentUpdateEntity documentUpdateEntity = (DocumentUpdateEntity) arangoTemplate .update(documentCreateEntity.getId(), newEmpDoc, docUpdateOptions); System.out.println("\nage attribute is added and firstName is updated in the document\n"); System.out.println("\nid : " + documentUpdateEntity.getId()); System.out.println("key : " + documentUpdateEntity.getKey()); System.out.println("revision : " + documentUpdateEntity.getRev()); System.out.println("doc : " + documentUpdateEntity.getNew()); }; } }

Total project structure looks like below.


 

 

 

Run App.java, you will see below messages in console.

 

id : hashMap/35151
key : 35151
revision : _cUkx71u---
doc : {"_key":"35151","_id":"hashMap\/35151","_rev":"_cUkx71u---","firstName":"Shanmukha Rao","lastName":"Kummari","id":1}

age attribute is added and firstName is updated in the document


id : hashMap/35151
key : 35151
revision : _cUkx73O---
doc : {"_key":"35151","_id":"hashMap\/35151","_rev":"_cUkx73O---","firstName":"Jaideep","lastName":"Kummari","id":1,"age":35}

You can download complete working application from below link.

https://github.com/harikrishna553/springboot/tree/master/arangodb/arango-template-update-document



Previous                                                    Next                                                    Home