Example usage for com.mongodb.client.model IndexOptions IndexOptions

List of usage examples for com.mongodb.client.model IndexOptions IndexOptions

Introduction

In this page you can find the example usage for com.mongodb.client.model IndexOptions IndexOptions.

Prototype

IndexOptions

Source Link

Usage

From source file:org.openo.commontosca.inventory.core.mongo.handler.model.MongoModelUpdateRequestHandler.java

License:Apache License

private void ensureDataCollectionIndex(MongoCollection<Document> dataCollection, List<ValueMap> allIndexes,
        String attributeName, boolean hasIndex, boolean uniqueIndex) throws Exception {
    Optional<ValueMap> findIndex = allIndexes.stream().filter(map -> {
        return map.requireMap("key").get(attributeName) != null;
    }).findAny();/*from   www . jav  a  2  s .c  o m*/
    if (findIndex.isPresent()) {
        ValueMap theIndex = findIndex.get();
        String indexName = theIndex.requireString("name");
        if (hasIndex) {
            boolean oldIsUnique = theIndex.optBoolean("unique", false);
            if (uniqueIndex != oldIsUnique) {
                DeferredSingleResult.<Void>execute(deferred -> {
                    dataCollection.dropIndex(indexName, deferred);
                });
                allIndexes.removeIf(map -> {
                    return map.requireMap("key").get(attributeName) != null;
                });
                this.ensureDataCollectionIndex(dataCollection, allIndexes, attributeName, hasIndex,
                        uniqueIndex);
            }
        } else {
            DeferredSingleResult.<Void>execute(deferred -> {
                dataCollection.dropIndex(indexName, deferred);
            });
        }
    } else if (hasIndex) {
        DeferredSingleResult.<String>execute(deferred -> {
            dataCollection.createIndex(Indexes.ascending(attributeName), new IndexOptions().unique(uniqueIndex),
                    deferred);
        });
    }
}

From source file:org.radarcns.mongo.util.MongoHelper.java

License:Apache License

/**
 * Creates given index on the collection, if it is not already created for given collection.
 * Having indexes created in background prevents other operations being blocked.
 * @param collection mongoCollection to index.
 * @param index index to be created.//from   ww w.  j a  v  a2  s  .  c  om
 */
private static void createIndexIfNotAvailable(MongoCollection<Document> collection, Bson index) {
    if (indexMap.containsKey(collection.getNamespace().getCollectionName())) {
        List<String> availableIndexes = indexMap.get(collection.getNamespace().getCollectionName());
        if (!availableIndexes.contains(index.toString())) {
            collection.createIndex(index, new IndexOptions().background(true));
            availableIndexes.add(index.toString());
        }

    } else {
        collection.createIndex(index, new IndexOptions().background(true));
        List<String> indexList = new ArrayList<>();
        indexList.add(index.toString());
        indexMap.put(collection.getNamespace().getCollectionName(), indexList);
    }
}

From source file:org.restheart.db.IndexDAO.java

License:Open Source License

/**
 *
 * @param dbName//from   w  w w  .  ja v a  2s  .c  om
 * @param collection
 * @param keys
 * @param options
 */
void createIndex(String dbName, String collection, BsonDocument keys, BsonDocument options) {
    if (options == null) {
        client.getDatabase(dbName).getCollection(collection).createIndex(keys);
    } else {
        // need to find a way to get IndexOptions from json
        IndexOptions io = new IndexOptions();

        io.background(true);

        client.getDatabase(dbName).getCollection(collection).createIndex(keys, getIndexOptions(options));
    }
}

From source file:org.restheart.db.IndexDAO.java

License:Open Source License

IndexOptions getIndexOptions(BsonDocument options) {
    IndexOptions ret = new IndexOptions();

    //***Options for All Index Types
    //name  string
    if (options.containsKey("name") && options.get("name").isString()) {
        ret.name(options.get("name").asString().getValue());
    }/*  w  ww  .jav  a 2  s.com*/

    //background    boolean
    if (options.containsKey("background") && options.get("background").isBoolean()) {
        ret.background(options.get("background").asBoolean().getValue());
    }

    //expireAfterSeconds    integer
    if (options.containsKey("expireAfterSeconds") && options.get("expireAfterSeconds").isInt32()) {
        ret.expireAfter(0l + options.get("expireAfterSeconds").asInt32().getValue(), TimeUnit.SECONDS);
    }

    //partialFilterExpression   document
    if (options.containsKey("partialFilterExpression") && options.get("partialFilterExpression").isDocument()) {
        ret.partialFilterExpression(options.get("partialFilterExpression").asDocument());
    }

    //storageEngine document
    if (options.containsKey("storageEngine") && options.get("storageEngine").isDocument()) {
        ret.storageEngine(options.get("storageEngine").asDocument());
    }

    //unique   boolean
    if (options.containsKey("unique") && options.get("unique").isBoolean()) {
        ret.unique(options.get("unique").asBoolean().getValue());
    }

    //sparse    boolean
    if (options.containsKey("sparse") && options.get("sparse").isBoolean()) {
        ret.sparse(options.get("sparse").asBoolean().getValue());
    }

    //***Options for text Indexes
    //weights   document
    if (options.containsKey("weights") && options.get("weights").isDocument()) {
        ret.weights(options.get("weights").asDocument());
    }
    //default_language   string
    if (options.containsKey("default_language") && options.get("default_language").isString()) {
        ret.defaultLanguage(options.get("default_language").asString().getValue());
    }

    //language_override   string
    if (options.containsKey("language_override") && options.get("language_override").isString()) {
        ret.languageOverride(options.get("language_override").asString().getValue());
    }

    //textIndexVersion   integer
    if (options.containsKey("textIndexVersion") && options.get("textIndexVersion").isInt32()) {
        ret.textVersion(options.get("textIndexVersion").asInt32().getValue());
    }

    //***Options for 2dsphere Indexes
    //2dsphereIndexVersion   integer
    if (options.containsKey("2dsphereIndexVersion") && options.get("2dsphereIndexVersion").isInt32()) {
        ret.sphereVersion(options.get("2dsphereIndexVersion").asInt32().getValue());
    }

    //***Options for 2d Indexes
    //bits   integer
    if (options.containsKey("bits") && options.get("bits").isInt32()) {
        ret.bits(options.get("bits").asInt32().getValue());
    }

    //min   number
    if (options.containsKey("min") && options.get("min").isDouble()) {
        ret.min(options.get("min").asDouble().getValue());
    }

    //max   number
    if (options.containsKey("max") && options.get("max").isDouble()) {
        ret.max(options.get("max").asDouble().getValue());
    }

    //***Options for geoHaystack Indexes
    //bucketSize   number
    if (options.containsKey("bucketSize") && options.get("bucketSize").isDouble()) {
        ret.bucketSize(options.get("bucketSize").asDouble().getValue());
    }

    return ret;
}

From source file:org.springframework.data.mongodb.core.IndexConverters.java

License:Apache License

private static Converter<IndexDefinition, IndexOptions> getIndexDefinitionIndexOptionsConverter() {

    return indexDefinition -> {

        Document indexOptions = indexDefinition.getIndexOptions();
        IndexOptions ops = new IndexOptions();

        if (indexOptions.containsKey("name")) {
            ops = ops.name(indexOptions.get("name").toString());
        }//from   www . java  2s .c o  m
        if (indexOptions.containsKey("unique")) {
            ops = ops.unique((Boolean) indexOptions.get("unique"));
        }
        if (indexOptions.containsKey("sparse")) {
            ops = ops.sparse((Boolean) indexOptions.get("sparse"));
        }
        if (indexOptions.containsKey("background")) {
            ops = ops.background((Boolean) indexOptions.get("background"));
        }
        if (indexOptions.containsKey("expireAfterSeconds")) {
            ops = ops.expireAfter((Long) indexOptions.get("expireAfterSeconds"), TimeUnit.SECONDS);
        }
        if (indexOptions.containsKey("min")) {
            ops = ops.min(((Number) indexOptions.get("min")).doubleValue());
        }
        if (indexOptions.containsKey("max")) {
            ops = ops.max(((Number) indexOptions.get("max")).doubleValue());
        }
        if (indexOptions.containsKey("bits")) {
            ops = ops.bits((Integer) indexOptions.get("bits"));
        }
        if (indexOptions.containsKey("bucketSize")) {
            ops = ops.bucketSize(((Number) indexOptions.get("bucketSize")).doubleValue());
        }
        if (indexOptions.containsKey("default_language")) {
            ops = ops.defaultLanguage(indexOptions.get("default_language").toString());
        }
        if (indexOptions.containsKey("language_override")) {
            ops = ops.languageOverride(indexOptions.get("language_override").toString());
        }
        if (indexOptions.containsKey("weights")) {
            ops = ops.weights((org.bson.Document) indexOptions.get("weights"));
        }

        for (String key : indexOptions.keySet()) {
            if (ObjectUtils.nullSafeEquals("2dsphere", indexOptions.get(key))) {
                ops = ops.sphereVersion(2);
            }
        }

        if (indexOptions.containsKey("partialFilterExpression")) {
            ops = ops.partialFilterExpression((org.bson.Document) indexOptions.get("partialFilterExpression"));
        }

        if (indexOptions.containsKey("collation")) {
            ops = ops.collation(fromDocument(indexOptions.get("collation", Document.class)));
        }

        return ops;
    };
}

From source file:org.wso2.extension.siddhi.store.mongodb.util.MongoTableUtils.java

License:Open Source License

/**
 * Utility method which can be used to check if the given primary key is valid i.e. non empty
 * and is made up of attributes and return an index model when PrimaryKey is valid.
 *
 * @param primaryKey     the PrimaryKey annotation which contains the primary key attributes.
 * @param attributeNames List containing names of the attributes.
 * @return List of String with primary key attributes.
 *//*from  w ww  .j  a v a2 s. c o  m*/
public static IndexModel extractPrimaryKey(Annotation primaryKey, List<String> attributeNames) {
    if (primaryKey == null) {
        return null;
    }
    Document primaryKeyIndex = new Document();
    primaryKey.getElements().forEach(element -> {
        if (!isEmpty(element.getValue()) && attributeNames.contains(element.getValue())) {
            primaryKeyIndex.append(element.getValue(), 1);
        } else {
            throw new SiddhiAppCreationException(
                    "Annotation '" + primaryKey.getName() + "' contains " + "value '" + element.getValue()
                            + "' which is not present in the attributes of the " + "Event Table.");
        }
    });
    return new IndexModel(primaryKeyIndex, new IndexOptions().unique(true));
}

From source file:org.wso2.extension.siddhi.store.mongodb.util.MongoTableUtils.java

License:Open Source License

/**
 * Utility method which can be used to create an IndexModel.
 *
 * @param fieldName   the attribute on which the index is to be created.
 * @param sortOrder   the sort order of the index to be created.
 * @param indexOption json string of the options of the index to be created.
 * @return IndexModel.//w w w . j  a va  2 s  .  co  m
 */
private static IndexModel createIndexModel(String fieldName, Integer sortOrder, String indexOption) {
    Document indexDocument = new Document(fieldName, sortOrder);
    if (indexOption == null) {
        return new IndexModel(indexDocument);
    } else {
        IndexOptions indexOptions = new IndexOptions();
        Document indexOptionDocument;
        try {
            indexOptionDocument = Document.parse(indexOption);
            for (Map.Entry<String, Object> indexEntry : indexOptionDocument.entrySet()) {
                Object value = indexEntry.getValue();
                switch (indexEntry.getKey()) {
                case "unique":
                    indexOptions.unique(Boolean.parseBoolean(value.toString()));
                    break;
                case "background":
                    indexOptions.background(Boolean.parseBoolean(value.toString()));
                    break;
                case "name":
                    indexOptions.name(value.toString());
                    break;
                case "sparse":
                    indexOptions.sparse(Boolean.parseBoolean(value.toString()));
                    break;
                case "expireAfterSeconds":
                    indexOptions.expireAfter(Long.parseLong(value.toString()), TimeUnit.SECONDS);
                    break;
                case "version":
                    indexOptions.version(Integer.parseInt(value.toString()));
                    break;
                case "weights":
                    indexOptions.weights((Bson) value);
                    break;
                case "languageOverride":
                    indexOptions.languageOverride(value.toString());
                    break;
                case "defaultLanguage":
                    indexOptions.defaultLanguage(value.toString());
                    break;
                case "textVersion":
                    indexOptions.textVersion(Integer.parseInt(value.toString()));
                    break;
                case "sphereVersion":
                    indexOptions.sphereVersion(Integer.parseInt(value.toString()));
                    break;
                case "bits":
                    indexOptions.bits(Integer.parseInt(value.toString()));
                    break;
                case "min":
                    indexOptions.min(Double.parseDouble(value.toString()));
                    break;
                case "max":
                    indexOptions.max(Double.parseDouble(value.toString()));
                    break;
                case "bucketSize":
                    indexOptions.bucketSize(Double.parseDouble(value.toString()));
                    break;
                case "partialFilterExpression":
                    indexOptions.partialFilterExpression((Bson) value);
                    break;
                case "collation":
                    DBObject collationOptions = (DBObject) value;
                    Collation.Builder builder = Collation.builder();
                    for (String collationKey : collationOptions.keySet()) {
                        String collationObj = value.toString();
                        switch (collationKey) {
                        case "locale":
                            builder.locale(collationObj);
                            break;
                        case "caseLevel":
                            builder.caseLevel(Boolean.parseBoolean(collationObj));
                            break;
                        case "caseFirst":
                            builder.collationCaseFirst(CollationCaseFirst.fromString(collationObj));
                            break;
                        case "strength":
                            builder.collationStrength(CollationStrength.valueOf(collationObj));
                            break;
                        case "numericOrdering":
                            builder.numericOrdering(Boolean.parseBoolean(collationObj));
                            break;
                        case "normalization":
                            builder.normalization(Boolean.parseBoolean(collationObj));
                            break;
                        case "backwards":
                            builder.backwards(Boolean.parseBoolean(collationObj));
                            break;
                        case "alternate":
                            builder.collationAlternate(CollationAlternate.fromString(collationObj));
                            break;
                        case "maxVariable":
                            builder.collationMaxVariable(CollationMaxVariable.fromString(collationObj));
                            break;
                        default:
                            log.warn("Annotation 'IndexBy' for the field '" + fieldName + "' contains "
                                    + "unknown 'Collation' Option key : '" + collationKey + "'. Please "
                                    + "check your query and try again.");
                            break;
                        }
                    }
                    if (builder.build().getLocale() != null) {
                        indexOptions.collation(builder.build());
                    } else {
                        throw new MongoTableException("Annotation 'IndexBy' for the field '" + fieldName + "'"
                                + " do not contain option for locale. Please check your query and try again.");
                    }
                    break;
                case "storageEngine":
                    indexOptions.storageEngine((Bson) value);
                    break;
                default:
                    log.warn("Annotation 'IndexBy' for the field '" + fieldName + "' contains unknown option "
                            + "key : '" + indexEntry.getKey() + "'. Please check your query and try again.");
                    break;
                }
            }
        } catch (JsonParseException | NumberFormatException e) {
            throw new MongoTableException("Annotation 'IndexBy' for the field '" + fieldName + "' contains "
                    + "illegal value(s) for index option. Please check your query and try again.", e);
        }
        return new IndexModel(indexDocument, indexOptions);
    }
}

From source file:rapture.table.mongodb.MongoIndexHandler.java

License:Open Source License

private void createIt(IndexDefinition indexDefinition, boolean force, String indexName,
        MongoCollection<Document> collection) {
    // bug in mongo driver: need to set ns explicitly
    // String ns = collection.getDB() + "." + collection.getName();

    Document index = new Document();
    for (FieldDefinition f : indexDefinition.getFields()) {
        index.put(f.getName(), 1);//from ww  w .ja v  a 2s  .  c o m
    }
    IndexOptions options = new IndexOptions().name(indexName).background(!force);
    collection.createIndex(index, options);
}

From source file:ro.pippo.session.mongodb.MongoDBSessionDataStorage.java

License:Apache License

/**
 * Create TTL index/*from   w  ww . j  a  va  2s  .c  om*/
 *
 * @param idleTime idle time in seconds
 * @see https://docs.mongodb.com/manual/core/index-ttl/
 */
private void createIndex(long idleTime) {
    try {
        this.sessions.createIndex(new Document(SESSION_TTL, 1),
                new IndexOptions().expireAfter(idleTime, TimeUnit.SECONDS).name(SESSION_INDEX_NAME));
    } catch (MongoException ex) {//update idle time
        this.sessions.dropIndex(SESSION_INDEX_NAME);
        this.sessions.createIndex(new Document(SESSION_TTL, 1),
                new IndexOptions().expireAfter(idleTime, TimeUnit.SECONDS).name(SESSION_INDEX_NAME));
    }
}

From source file:tools.devnull.boteco.persistence.request.MongoRequestRepository.java

License:Open Source License

public MongoRequestRepository(MongoDatabase database, Long minutesToExpire) {
    this.requests = database.getCollection("requests");
    try {/*from   ww w . j a  v  a  2 s. co  m*/
        this.requests.dropIndex("createdAt_1");
        logger.info("Dropped index 'createdAt', creating a new one.");
    } catch (MongoCommandException e) {
        logger.info("Index for 'createdAt' doesn't exist, creating index.");
    }
    this.requests.createIndex(new Document("createdAt", 1),
            new IndexOptions().expireAfter(minutesToExpire, TimeUnit.MINUTES));
    this.gson = new Gson();
}