Search in sources :

Example 16 with Key

use of org.hypertrace.core.documentstore.Key in project document-store by hypertrace.

the class PostgresDocStoreTest method testBulkUpsertAndReturn.

@Test
public void testBulkUpsertAndReturn() throws IOException {
    Collection collection = datastore.getCollection(COLLECTION_NAME);
    Map<Key, Document> bulkMap = new HashMap<>();
    bulkMap.put(new SingleValueKey("default", "testKey1"), Utils.createDocument("name", "Bob"));
    bulkMap.put(new SingleValueKey("default", "testKey2"), Utils.createDocument("name", "Alice"));
    bulkMap.put(new SingleValueKey("default", "testKey3"), Utils.createDocument("name", "Alice"));
    bulkMap.put(new SingleValueKey("default", "testKey4"), Utils.createDocument("name", "Bob"));
    bulkMap.put(new SingleValueKey("default", "testKey5"), Utils.createDocument("name", "Alice"));
    bulkMap.put(new SingleValueKey("default", "testKey6"), Utils.createDocument("email", "bob@example.com"));
    Iterator<Document> iterator = collection.bulkUpsertAndReturnOlderDocuments(bulkMap);
    // Initially there shouldn't be any documents.
    Assertions.assertFalse(iterator.hasNext());
    // The operation should be idempotent, so go ahead and try again.
    iterator = collection.bulkUpsertAndReturnOlderDocuments(bulkMap);
    List<Document> documents = new ArrayList<>();
    while (iterator.hasNext()) {
        documents.add(iterator.next());
    }
    Assertions.assertEquals(6, documents.size());
    {
        // empty query returns all the documents
        Query query = new Query();
        Assertions.assertEquals(6, collection.total(query));
    }
    {
        Query query = new Query();
        query.setFilter(Filter.eq("name", "Bob"));
        Assertions.assertEquals(2, collection.total(query));
    }
    {
        // limit should not affect the total
        Query query = new Query();
        query.setFilter(Filter.eq("name", "Bob"));
        query.setLimit(1);
        Assertions.assertEquals(2, collection.total(query));
    }
}
Also used : SingleValueKey(org.hypertrace.core.documentstore.SingleValueKey) Query(org.hypertrace.core.documentstore.Query) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Collection(org.hypertrace.core.documentstore.Collection) Document(org.hypertrace.core.documentstore.Document) Key(org.hypertrace.core.documentstore.Key) SingleValueKey(org.hypertrace.core.documentstore.SingleValueKey) Test(org.junit.jupiter.api.Test)

Example 17 with Key

use of org.hypertrace.core.documentstore.Key in project document-store by hypertrace.

the class PostgresCollection method bulkUpsertAndReturnOlderDocuments.

@Override
public CloseableIterator<Document> bulkUpsertAndReturnOlderDocuments(Map<Key, Document> documents) throws IOException {
    String query = null;
    try {
        String collect = documents.keySet().stream().map(val -> "'" + val.toString() + "'").collect(Collectors.joining(", "));
        String space = " ";
        query = new StringBuilder("SELECT * FROM").append(space).append(collectionName).append(" WHERE ").append(ID).append(" IN ").append("(").append(collect).append(")").toString();
        PreparedStatement preparedStatement = client.prepareStatement(query);
        ResultSet resultSet = preparedStatement.executeQuery();
        // Now go ahead and bulk upsert the documents.
        int[] updateCounts = bulkUpsertImpl(documents);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Write result: {}", Arrays.toString(updateCounts));
        }
        return new PostgresResultIterator(resultSet);
    } catch (IOException e) {
        LOGGER.error("SQLException bulk inserting documents. documents: {}", documents, e);
    } catch (SQLException e) {
        LOGGER.error("SQLException querying documents. query: {}", query, e);
    }
    throw new IOException("Could not bulk upsert the documents.");
}
Also used : Document(org.hypertrace.core.documentstore.Document) Arrays(java.util.Arrays) Connection(java.sql.Connection) SneakyThrows(lombok.SneakyThrows) BatchUpdateException(java.sql.BatchUpdateException) Filter(org.hypertrace.core.documentstore.Filter) LoggerFactory(org.slf4j.LoggerFactory) Query(org.hypertrace.core.documentstore.Query) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) Collection(org.hypertrace.core.documentstore.Collection) HashSet(java.util.HashSet) SQLException(java.sql.SQLException) Key(org.hypertrace.core.documentstore.Key) ResultSet(java.sql.ResultSet) Map(java.util.Map) CloseableIterator(org.hypertrace.core.documentstore.CloseableIterator) NoSuchElementException(java.util.NoSuchElementException) BulkArrayValueUpdateRequest(org.hypertrace.core.documentstore.BulkArrayValueUpdateRequest) BulkUpdateRequest(org.hypertrace.core.documentstore.BulkUpdateRequest) BulkUpdateResult(org.hypertrace.core.documentstore.BulkUpdateResult) Logger(org.slf4j.Logger) Timestamp(java.sql.Timestamp) JSONDocument(org.hypertrace.core.documentstore.JSONDocument) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Set(java.util.Set) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) PreparedStatement(java.sql.PreparedStatement) Collectors(java.util.stream.Collectors) List(java.util.List) UpdateResult(org.hypertrace.core.documentstore.UpdateResult) Statement(java.sql.Statement) VisibleForTesting(com.google.common.annotations.VisibleForTesting) CreateResult(org.hypertrace.core.documentstore.CreateResult) SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) IOException(java.io.IOException)

Example 18 with Key

use of org.hypertrace.core.documentstore.Key in project entity-service by hypertrace.

the class EntityQueryServiceImpl method doBulkUpdate.

private void doBulkUpdate(RequestContext requestContext, Map<String, EntityUpdateInfo> entitiesMap) throws Exception {
    Map<Key, Map<String, Document>> entitiesUpdateMap = new HashMap<>();
    for (String entityId : entitiesMap.keySet()) {
        Map<String, Document> transformedUpdateOperations = transformUpdateOperations(entitiesMap.get(entityId).getUpdateOperationList(), requestContext);
        if (transformedUpdateOperations.isEmpty()) {
            continue;
        }
        entitiesUpdateMap.put(new SingleValueKey(requestContext.getTenantId().orElseThrow(), entityId), transformedUpdateOperations);
    }
    if (entitiesUpdateMap.isEmpty()) {
        LOG.error("There are no entities to update!");
        return;
    }
    try {
        entitiesCollection.bulkUpdateSubDocs(entitiesUpdateMap);
    } catch (Exception e) {
        LOG.error("Failed to update entities {}", entitiesMap, e);
        throw e;
    }
}
Also used : SingleValueKey(org.hypertrace.core.documentstore.SingleValueKey) HashMap(java.util.HashMap) Document(org.hypertrace.core.documentstore.Document) JSONDocument(org.hypertrace.core.documentstore.JSONDocument) Map(java.util.Map) HashMap(java.util.HashMap) SingleValueKey(org.hypertrace.core.documentstore.SingleValueKey) Key(org.hypertrace.core.documentstore.Key) ServiceException(com.google.protobuf.ServiceException) ConversionException(org.hypertrace.entity.query.service.converter.ConversionException)

Example 19 with Key

use of org.hypertrace.core.documentstore.Key in project entity-service by hypertrace.

the class EntityQueryServiceImpl method bulkUpdateEntityArrayAttribute.

@Override
public void bulkUpdateEntityArrayAttribute(BulkEntityArrayAttributeUpdateRequest request, StreamObserver<BulkEntityArrayAttributeUpdateResponse> responseObserver) {
    RequestContext requestContext = RequestContext.CURRENT.get();
    String tenantId = requestContext.getTenantId().orElse(null);
    if (isNull(tenantId)) {
        responseObserver.onError(new ServiceException("Tenant id is missing in the request."));
        return;
    }
    try {
        Set<Key> keys = request.getEntityIdsList().stream().map(entityId -> new SingleValueKey(tenantId, entityId)).collect(Collectors.toCollection(LinkedHashSet::new));
        String attributeId = request.getAttribute().getColumnName();
        String subDocPath = entityAttributeMapping.getDocStorePathByAttributeId(requestContext, attributeId).orElseThrow(() -> new IllegalArgumentException("Unknown attribute " + attributeId));
        List<Document> subDocuments = request.getValuesList().stream().map(this::convertToJsonDocument).collect(toUnmodifiableList());
        BulkArrayValueUpdateRequest bulkArrayValueUpdateRequest = new BulkArrayValueUpdateRequest(keys, subDocPath + ARRAY_VALUE_PATH_SUFFIX, getMatchingOperation(request.getOperation()), subDocuments);
        entitiesCollection.bulkOperationOnArrayValue(bulkArrayValueUpdateRequest);
        responseObserver.onNext(BulkEntityArrayAttributeUpdateResponse.newBuilder().build());
        responseObserver.onCompleted();
    } catch (Exception e) {
        responseObserver.onError(e);
    }
}
Also used : DocumentParser(org.hypertrace.entity.data.service.DocumentParser) Function(org.hypertrace.entity.query.service.v1.Function) EntityQueryServiceImplBase(org.hypertrace.entity.query.service.v1.EntityQueryServiceGrpc.EntityQueryServiceImplBase) SneakyThrows(lombok.SneakyThrows) ResultSetChunk(org.hypertrace.entity.query.service.v1.ResultSetChunk) UpdateOperation(org.hypertrace.entity.query.service.v1.UpdateOperation) ServiceException(com.google.protobuf.ServiceException) ResultSetMetadata(org.hypertrace.entity.query.service.v1.ResultSetMetadata) LoggerFactory(org.slf4j.LoggerFactory) ConversionException(org.hypertrace.entity.query.service.converter.ConversionException) StreamObserver(io.grpc.stub.StreamObserver) Map(java.util.Map) RelationalExpression(org.hypertrace.core.documentstore.expression.impl.RelationalExpression) BulkEntityArrayAttributeUpdateResponse(org.hypertrace.entity.query.service.v1.BulkEntityArrayAttributeUpdateResponse) BulkEntityArrayAttributeUpdateRequest(org.hypertrace.entity.query.service.v1.BulkEntityArrayAttributeUpdateRequest) Objects.isNull(java.util.Objects.isNull) SingleValueKey(org.hypertrace.core.documentstore.SingleValueKey) DocStoreConverter(org.hypertrace.entity.service.util.DocStoreConverter) Filter(org.hypertrace.core.documentstore.query.Filter) Value(org.hypertrace.entity.query.service.v1.Value) Collections.emptyList(java.util.Collections.emptyList) BulkEntityUpdateRequest(org.hypertrace.entity.query.service.v1.BulkEntityUpdateRequest) Set(java.util.Set) StringUtils(org.hypertrace.entity.service.util.StringUtils) Collectors(java.util.stream.Collectors) Collectors.joining(java.util.stream.Collectors.joining) ColumnMetadata(org.hypertrace.entity.query.service.v1.ColumnMetadata) List(java.util.List) Lists.newArrayList(com.google.common.collect.Lists.newArrayList) Stream(java.util.stream.Stream) GrpcChannelRegistry(org.hypertrace.core.grpcutils.client.GrpcChannelRegistry) IN(org.hypertrace.core.documentstore.expression.operators.RelationalOperator.IN) TotalEntitiesRequest(org.hypertrace.entity.query.service.v1.TotalEntitiesRequest) Optional(java.util.Optional) EntityQueryRequest(org.hypertrace.entity.query.service.v1.EntityQueryRequest) TypeLiteral(com.google.inject.TypeLiteral) LiteralConstant(org.hypertrace.entity.query.service.v1.LiteralConstant) SetAttribute(org.hypertrace.entity.query.service.v1.SetAttribute) Row(org.hypertrace.entity.query.service.v1.Row) Document(org.hypertrace.core.documentstore.Document) RequestContext(org.hypertrace.core.grpcutils.context.RequestContext) DocStoreJsonFormat(org.hypertrace.entity.service.util.DocStoreJsonFormat) ENTITY_ATTRIBUTE_DOC_PREFIX(org.hypertrace.entity.query.service.EntityAttributeMapping.ENTITY_ATTRIBUTE_DOC_PREFIX) AliasProvider(org.hypertrace.entity.query.service.converter.AliasProvider) ConstantExpression(org.hypertrace.core.documentstore.expression.impl.ConstantExpression) EntityUpdateRequest(org.hypertrace.entity.query.service.v1.EntityUpdateRequest) HashMap(java.util.HashMap) Collection(org.hypertrace.core.documentstore.Collection) Collectors.toUnmodifiableList(java.util.stream.Collectors.toUnmodifiableList) ArrayList(java.util.ArrayList) Datastore(org.hypertrace.core.documentstore.Datastore) Converter(org.hypertrace.entity.query.service.converter.Converter) Key(org.hypertrace.core.documentstore.Key) ConverterModule(org.hypertrace.entity.query.service.converter.ConverterModule) EntityUpdateInfo(org.hypertrace.entity.query.service.v1.BulkEntityUpdateRequest.EntityUpdateInfo) AttributeValue(org.hypertrace.entity.data.service.v1.AttributeValue) EntityServiceConstants(org.hypertrace.entity.service.constants.EntityServiceConstants) VALUES_FIELD_NUMBER(org.hypertrace.entity.data.service.v1.AttributeValueList.VALUES_FIELD_NUMBER) Entity(org.hypertrace.entity.data.service.v1.Entity) DocumentConverter(org.hypertrace.entity.query.service.converter.response.DocumentConverter) LinkedHashSet(java.util.LinkedHashSet) TotalEntitiesResponse(org.hypertrace.entity.query.service.v1.TotalEntitiesResponse) BulkArrayValueUpdateRequest(org.hypertrace.core.documentstore.BulkArrayValueUpdateRequest) IdentifierExpression(org.hypertrace.core.documentstore.expression.impl.IdentifierExpression) ColumnIdentifier(org.hypertrace.entity.query.service.v1.ColumnIdentifier) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) Config(com.typesafe.config.Config) JSONDocument(org.hypertrace.core.documentstore.JSONDocument) Printer(org.hypertrace.entity.service.util.DocStoreJsonFormat.Printer) VALUE_LIST_FIELD_NUMBER(org.hypertrace.entity.data.service.v1.AttributeValue.VALUE_LIST_FIELD_NUMBER) AttributeValueList(org.hypertrace.entity.data.service.v1.AttributeValueList) Injector(com.google.inject.Injector) Selection(org.hypertrace.core.documentstore.query.Selection) Query(org.hypertrace.entity.data.service.v1.Query) Expression(org.hypertrace.entity.query.service.v1.Expression) RAW_ENTITIES_COLLECTION(org.hypertrace.entity.service.constants.EntityCollectionConstants.RAW_ENTITIES_COLLECTION) ValueType(org.hypertrace.entity.query.service.v1.ValueType) Guice(com.google.inject.Guice) VisibleForTesting(com.google.common.annotations.VisibleForTesting) ValueCase(org.hypertrace.entity.query.service.v1.Expression.ValueCase) Collections(java.util.Collections) SingleValueKey(org.hypertrace.core.documentstore.SingleValueKey) ServiceException(com.google.protobuf.ServiceException) RequestContext(org.hypertrace.core.grpcutils.context.RequestContext) Document(org.hypertrace.core.documentstore.Document) JSONDocument(org.hypertrace.core.documentstore.JSONDocument) BulkArrayValueUpdateRequest(org.hypertrace.core.documentstore.BulkArrayValueUpdateRequest) SingleValueKey(org.hypertrace.core.documentstore.SingleValueKey) Key(org.hypertrace.core.documentstore.Key) ServiceException(com.google.protobuf.ServiceException) ConversionException(org.hypertrace.entity.query.service.converter.ConversionException)

Example 20 with Key

use of org.hypertrace.core.documentstore.Key in project entity-service by hypertrace.

the class EntityDataServiceImpl method getAndUpsertEntities.

@Override
public void getAndUpsertEntities(Entities request, StreamObserver<Entity> responseObserver) {
    String tenantId = RequestContext.CURRENT.get().getTenantId().orElse(null);
    if (tenantId == null) {
        responseObserver.onError(new ServiceException("Tenant id is missing in the request."));
        return;
    }
    try {
        Map<Key, Document> documentMap = new HashMap<>();
        List<Entity> updatedEntities = new ArrayList<>();
        for (Entity entity : request.getEntityList()) {
            Entity normalizedEntity = this.entityNormalizer.normalize(tenantId, entity);
            updatedEntities.add(normalizedEntity);
            Document doc = convertEntityToDocument(normalizedEntity);
            Key key = this.entityNormalizer.getEntityDocKey(tenantId, normalizedEntity);
            documentMap.put(key, doc);
        }
        List<Entity> existingEntities = Streams.stream(entitiesCollection.bulkUpsertAndReturnOlderDocuments(documentMap)).flatMap(document -> PARSER.<Entity>parseOrLog(document, Entity.newBuilder()).stream()).map(Entity::toBuilder).map(builder -> builder.setTenantId(tenantId)).map(Entity.Builder::build).collect(Collectors.toList());
        existingEntities.forEach(responseObserver::onNext);
        responseObserver.onCompleted();
        entityChangeEventGenerator.sendChangeNotification(RequestContext.CURRENT.get(), existingEntities, updatedEntities);
    } catch (IOException e) {
        LOG.error("Failed to bulk upsert entities", e);
        responseObserver.onError(e);
    }
}
Also used : EnrichedEntity(org.hypertrace.entity.data.service.v1.EnrichedEntity) Entity(org.hypertrace.entity.data.service.v1.Entity) ServiceException(com.google.protobuf.ServiceException) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) IOException(java.io.IOException) Document(org.hypertrace.core.documentstore.Document) JSONDocument(org.hypertrace.core.documentstore.JSONDocument) Key(org.hypertrace.core.documentstore.Key)

Aggregations

Key (org.hypertrace.core.documentstore.Key)22 Document (org.hypertrace.core.documentstore.Document)19 JSONDocument (org.hypertrace.core.documentstore.JSONDocument)17 HashMap (java.util.HashMap)14 ArrayList (java.util.ArrayList)12 Map (java.util.Map)12 Collection (org.hypertrace.core.documentstore.Collection)9 SingleValueKey (org.hypertrace.core.documentstore.SingleValueKey)9 ServiceException (com.google.protobuf.ServiceException)8 IOException (java.io.IOException)6 BulkUpdateResult (org.hypertrace.core.documentstore.BulkUpdateResult)6 BulkArrayValueUpdateRequest (org.hypertrace.core.documentstore.BulkArrayValueUpdateRequest)5 Query (org.hypertrace.core.documentstore.Query)5 Entity (org.hypertrace.entity.data.service.v1.Entity)5 JsonNode (com.fasterxml.jackson.databind.JsonNode)4 MongoCollection (com.mongodb.client.MongoCollection)4 List (java.util.List)4 Collectors (java.util.stream.Collectors)4 Datastore (org.hypertrace.core.documentstore.Datastore)4 Test (org.junit.jupiter.api.Test)4