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.eclipse.ditto.services.utils.persistence.mongo.indices.Index.java

License:Open Source License

/**
 * Creates a new {@link IndexModel}, which can be used for creating indices using MongoDB Java drivers.
 *
 * @return the created {@link IndexModel}
 */// ww  w  . j  a v a 2  s .  c  om
public IndexModel toIndexModel() {
    final IndexOptions options = new IndexOptions().name(name).unique(unique).sparse(sparse)
            .background(background);

    if (!partialFilterExpression.isEmpty()) {
        options.partialFilterExpression(partialFilterExpression);
    }

    getExpireAfterSeconds().ifPresent(n -> options.expireAfter(n, TimeUnit.SECONDS));

    return new IndexModel(keys, options);
}

From source file:org.gennai.gungnir.metastore.MongoDbMetaStore.java

License:Apache License

private void createIndexUserAccount() throws MetaStoreException {
    try {//from   ww w .ja va 2 s . com
        userAccountCollection.createIndex(new Document("name", 1), new IndexOptions().unique(true));
    } catch (MongoException e) {
        LOG.error("Failed to ensure index of user account collection", e);
        throw new MetaStoreException("Failed to ensure index user account collection", e);
    }
}

From source file:org.gennai.gungnir.metastore.MongoDbMetaStore.java

License:Apache License

private void createIndexSchema() throws MetaStoreException {
    try {/*from  ww  w .j a  v  a 2  s .c  o  m*/
        schemaCollection.createIndex(new Document("name", 1).append("owner", 1),
                new IndexOptions().unique(true));
    } catch (MongoException e) {
        LOG.error("Failed to ensure index of schema collection", e);
        throw new MetaStoreException("Failed to ensure index schema collection", e);
    }
}

From source file:org.gennai.gungnir.metastore.MongoDbMetaStore.java

License:Apache License

private void createIndexTopology() throws MetaStoreException {
    try {//www.j  a  v a2 s. c  o  m
        topologyCollection.createIndex(new Document("name", 1).append("owner", 1),
                new IndexOptions().unique(true));
    } catch (MongoException e) {
        LOG.error("Failed to ensure index of topology collection", e);
        throw new MetaStoreException("Failed to ensure index topology collection", e);
    }
}

From source file:org.gennai.gungnir.topology.processor.MongoPersistProcessor.java

License:Apache License

@Override
public void open(GungnirConfig config, GungnirContext context, OperatorContext operatorContext,
        Map<String, List<String>> outputFieldNames) throws ProcessorException {
    dbName = context.replaceVariable(dbName);
    collectionName = context.replaceVariable(collectionName);
    this.outputFieldNames = outputFieldNames;

    if (keyFieldNames != null) {
        keyFieldsIndexes = Maps.newHashMap();
        for (Map.Entry<String, List<String>> entry : outputFieldNames.entrySet()) {
            int[] index = new int[keyFieldNames.length];
            Arrays.fill(index, -1);
            for (int i = 0; i < keyFieldNames.length; i++) {
                for (int j = 0; j < entry.getValue().size(); j++) {
                    if (entry.getValue().get(j).equals(keyFieldNames[i])) {
                        index[i] = j;/*ww w. j  a  va 2 s  . c  om*/
                        break;
                    }
                }
                if (index[i] < 0) {
                    throw new ProcessorException("Can't found key field '" + keyFieldNames[i] + "'");
                }
            }
            keyFieldsIndexes.put(entry.getKey(), index);
        }
    }

    List<String> servers = config.getList(MONGO_PERSIST_SERVERS);
    List<ServerAddress> addresses = Lists.newArrayListWithCapacity(servers.size());
    for (String server : servers) {
        addresses.add(new ServerAddress(server));
    }
    mongoClient = new MongoClient(addresses);
    MongoDatabase db = mongoClient.getDatabase(dbName);
    collection = db.getCollection(collectionName);

    if (autoIndexing && keyFieldNames != null) {
        Document doc = new Document();
        for (String keyFieldName : keyFieldNames) {
            doc.append(keyFieldName, 1);
        }

        collection.createIndex(doc, new IndexOptions().unique(true));
    }

    LOG.info("MongoPersistProcessor opened({})", this);
}

From source file:org.iotivity.cloud.accountserver.db.MongoDB.java

License:Open Source License

/**
 * API for creating index//  ww  w  .java2 s  . c  o m
 *
 * @param tableName
 *            collection name
 * @param keys
 *            key fields of collection
 */
public void createIndex(String tablename, ArrayList<String> keys) {

    Document doc = new Document();

    for (String key : keys) {

        doc.append(key, 1);
    }

    IndexOptions options = new IndexOptions();
    options.unique(true);

    db.getCollection(tablename).createIndex(doc, options);
}

From source file:org.jooby.mongodb.MongoSessionStore.java

License:Apache License

private void syncTtl() {
    if (!ttlSync.get()) {
        ttlSync.set(true);// w w w  .j  a  v  a 2  s  .  c o  m

        if (timeout <= 0) {
            return;
        }

        log.debug("creating session timeout index");
        if (existsIdx(SESSION_IDX)) {
            Document command = new Document("collMod", collection).append("index",
                    new Document("keyPattern", new Document("_accessedAt", 1)).append("expireAfterSeconds",
                            timeout));
            log.debug("{}", command);
            Document result = db.runCommand(command);
            log.debug("{}", result);
        } else {
            sessions.createIndex(new Document("_accessedAt", 1),
                    new IndexOptions().name(SESSION_IDX).expireAfter(timeout, TimeUnit.SECONDS));
        }
    }
}

From source file:org.netbeans.modules.mongodb.indexes.Index.java

License:Open Source License

public IndexOptions getOptions() {
    return new IndexOptions().name(getName()).background(globalOptions.isBackground())
            .unique(globalOptions.isUnique()).sparse(globalOptions.isSparse())
            .expireAfter(globalOptions.getExpireAfterSeconds(), TimeUnit.SECONDS)
            .version(globalOptions.getIndexVersion()).storageEngine(globalOptions.getStorageEngine())
            .weights(textOptions.getWeights()).defaultLanguage(textOptions.getDefaultLanguage())
            .languageOverride(textOptions.getLanguageOverride()).textVersion(textOptions.getIndexVersion())
            .sphereVersion(geo2DSphereOptions.getIndexVersion()).bits(geo2DOptions.getBits())
            .min(geo2DOptions.getMin()).max(geo2DOptions.getMax())
            .bucketSize(geoHaystackOptions.getBucketSize());
}

From source file:org.opencb.commons.datastore.mongodb.MongoDBCollection.java

License:Apache License

public QueryResult createIndex(Bson keys, ObjectMap options) {
    long start = startQuery();
    IndexOptions i = new IndexOptions();
    if (options.containsKey(UNIQUE)) {
        i.unique(options.getBoolean(UNIQUE));
    }//from w ww . j  a  v  a  2 s.  c om
    if (options.containsKey(BACKGROUND)) {
        i.background(options.getBoolean(BACKGROUND));
    }
    if (options.containsKey(SPARSE)) {
        i.sparse(options.getBoolean(SPARSE));
    }
    if (options.containsKey(NAME)) {
        i.name(options.getString(NAME));
    }

    mongoDBNativeQuery.createIndex(keys, i);
    QueryResult queryResult = endQuery(Collections.emptyList(), start);
    return queryResult;
}

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

License:Apache License

/**
 *
 * //from w w w .jav a 2 s .  c o  m
 * @param request
 * @throws Exception
 */
private void ensureModelCollection(Insert request) throws Exception {
    MongoCollection<Document> modelCollection = this.getDatabase(request)
            .getCollection(Model.MODEL_DEFAULT_COLLECTION_NAME);
    boolean noneMatch = DeferredSingleResult.<List<Document>>execute(deferred -> {
        modelCollection.listIndexes().into(new ArrayList<>(), deferred);
    }).stream().map(d -> {
        return ValueMap.wrap(d);
    }).noneMatch(v -> {
        return v.requireMap("key").get(ModelKey.NAME) != null;
    });
    if (noneMatch) {
        DeferredSingleResult.<String>execute(deferred -> {
            modelCollection.createIndex(Indexes.ascending(ModelKey.NAME.getKeyName()),
                    new IndexOptions().unique(true), deferred);
        });
    }
}