private void createTableMetadata(SchemaTableName schemaTableName, List<MongoColumnHandle> columns) throws TableNotFoundException { String schemaName = schemaTableName.getSchemaName(); String tableName = schemaTableName.getTableName(); MongoDatabase db = client.getDatabase(schemaName); Document metadata = new Document(TABLE_NAME_KEY, tableName); ArrayList<Document> fields = new ArrayList<>(); if (!columns.stream().anyMatch(c -> c.getName().equals("_id"))) { fields.add(new MongoColumnHandle("_id", OBJECT_ID, true).getDocument()); } fields.addAll(columns.stream() .map(MongoColumnHandle::getDocument) .collect(toList())); metadata.append(FIELDS_KEY, fields); MongoCollection<Document> schema = db.getCollection(schemaCollection); schema.createIndex(new Document(TABLE_NAME_KEY, 1), new IndexOptions().unique(true)); schema.insertOne(metadata); }
IndexOptions ops = new IndexOptions(); ops = ops.name(indexOptions.get("name").toString()); ops = ops.unique((Boolean) indexOptions.get("unique")); ops = ops.sparse((Boolean) indexOptions.get("sparse")); ops = ops.background((Boolean) indexOptions.get("background")); ops = ops.expireAfter((Long) indexOptions.get("expireAfterSeconds"), TimeUnit.SECONDS); ops = ops.min(((Number) indexOptions.get("min")).doubleValue()); ops = ops.max(((Number) indexOptions.get("max")).doubleValue()); ops = ops.bits((Integer) indexOptions.get("bits")); ops = ops.bucketSize(((Number) indexOptions.get("bucketSize")).doubleValue()); ops = ops.defaultLanguage(indexOptions.get("default_language").toString()); ops = ops.languageOverride(indexOptions.get("language_override").toString()); ops = ops.weights((org.bson.Document) indexOptions.get("weights")); ops = ops.sphereVersion(2); ops = ops.partialFilterExpression((org.bson.Document) indexOptions.get("partialFilterExpression"));
private static void createIndex(MongoConnection mongoConnection) { final IndexOptions indexOptions = new IndexOptions() .name(INDEX_NAME) .unique(true); mongoConnection.getMongoDatabase() .getCollection(COLLECTION_NAME) .createIndex(Indexes.ascending("name"), indexOptions); }
private void syncTtl() { if (!ttlSync.get()) { ttlSync.set(true); 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)); } } }
/** * Forces creation of an index on a set of fields, if one does not already * exist. * * @param collection the collection. * @param fields the name of the fields. * @param ascending {@code true} for an ascending, {@code false} for a * descending index. * @param unique whether values are unique. * @param sparse whether the index should be sparse. * @throws IllegalArgumentException if {@code fields} and {@code ascending} * arrays have different lengths. * @throws MongoException if the operation fails. */ static void createIndex(MongoCollection<?> collection, String[] fields, boolean[] ascending, boolean unique, boolean sparse) throws MongoException { checkArgument(fields.length == ascending.length); BasicDBObject index = new BasicDBObject(); for (int i = 0; i < fields.length; i++) { index.put(fields[i], ascending[i] ? 1 : -1); } IndexOptions options = new IndexOptions().unique(unique).sparse(sparse); collection.createIndex(index, options); }
/** * Creates a new {@link IndexModel}, which can be used for creating indices using MongoDB Java drivers. * * @return the created {@link IndexModel} */ public IndexModel toIndexModel() { final IndexOptions options = new IndexOptions() .name(name) .unique(unique) .sparse(sparse) .background(background); if (!partialFilterExpression.isEmpty()) { options.partialFilterExpression(partialFilterExpression); } return new IndexModel(keys, options); }
@Override public IndexOptions convert(Environment env, TraceInfo trace, Memory arg) throws Throwable { if (arg.isNull()) return null; ArrayMemory arr = arg.toValue(ArrayMemory.class); IndexOptions options = new IndexOptions(); if (arr.containsKey("background")) { options.background(arg.valueOfIndex("background").toBoolean()); } if (arr.containsKey("defaultLanguage")) { options.defaultLanguage(arg.valueOfIndex("defaultLanguage").toString()); } if (arr.containsKey("bits")) { options.bits(arg.valueOfIndex("bits").toInteger()); } if (arr.containsKey("name")) { options.name(arg.valueOfIndex("name").toString()); } if (arr.containsKey("max")) { options.max(arg.valueOfIndex("max").toDouble()); } if (arr.containsKey("min")) { options.min(arg.valueOfIndex("min").toDouble()); } if (arr.containsKey("languageOverride")) { options.languageOverride(arg.valueOfIndex("languageOverride").toString()); } if (arr.containsKey("sparse")) { options.sparse(arg.valueOfIndex("sparse").toBoolean()); } if (arr.containsKey("unique")) { options.unique(arg.valueOfIndex("unique").toBoolean()); } if (arr.containsKey("version")) { options.version(arg.valueOfIndex("version").toInteger()); } if (arr.containsKey("textVersion")) { options.textVersion(arg.valueOfIndex("textVersion").toInteger()); } if (arr.containsKey("sphereVersion")) { options.sphereVersion(arg.valueOfIndex("sphereVersion").toInteger()); } return options; }
@SuppressWarnings("deprecation") com.mongodb.client.model.IndexOptions convert(final IndexOptions options, final boolean background) { if (options.dropDups()) { LOG.warn("Support for dropDups has been removed from the server. Please remove this setting."); } com.mongodb.client.model.IndexOptions indexOptions = new com.mongodb.client.model.IndexOptions() .background(options.background() || background) .sparse(options.sparse()) .unique(options.unique()); if (!options.language().equals("")) { indexOptions.defaultLanguage(options.language()); } if (!options.languageOverride().equals("")) { indexOptions.languageOverride(options.languageOverride()); } if (!options.name().equals("")) { indexOptions.name(options.name()); } if (options.expireAfterSeconds() != -1) { indexOptions.expireAfter((long) options.expireAfterSeconds(), TimeUnit.SECONDS); } if (!options.partialFilter().equals("")) { indexOptions.partialFilterExpression(Document.parse(options.partialFilter())); } if (!options.collation().locale().equals("")) { indexOptions.collation(convert(options.collation())); } return indexOptions; }
IndexOptions indexOptions = new IndexOptions(); indexOptions.name( indexName ).unique( unique ).background( options.getBoolean( "background" , false ) ); indexOptions.sparse( !options.containsKey( "partialFilterExpression" ) ); indexOptions.partialFilterExpression( (Bson) options.get( "partialFilterExpression" ) ); indexOptions.expireAfter( options.getInteger( "expireAfterSeconds" ).longValue() , TimeUnit.SECONDS ); indexOptions.defaultLanguage( options.getString( "default_language" ) ); indexOptions.weights( (Bson) options.get( "weights" ) );
private void createTimestampIndexWithTTL(MongoCollection<Document> collection, String attribute, Long ttl) { IndexOptions options = new IndexOptions(); options.expireAfter(ttl, TimeUnit.SECONDS); createTimestampIndexWithOptions(collection, attribute, options); }
/** * Construct an instance with the given keys. * * @param keys the index keys */ public IndexModel(final Bson keys) { this(keys, new IndexOptions()); }
@Override protected final void ensureIndexes() { IndexOptions options = new IndexOptions().background(true); collection().createIndex(Indexes.compoundIndex(Indexes.ascending(JobStructure.JOB_TYPE.key()), Indexes.descending(JobStructure.STARTED.key())), options); collection().createIndex(Indexes.ascending(JobStructure.STARTED.key()), options); collection().createIndex(Indexes.ascending(JobStructure.LAST_UPDATED.key(), JobStructure.STOPPED.key()), options); }
IndexOptions indexOptions = new IndexOptions().name(FULLTEXT_INDEX_NAME).languageOverride(LANGUAGE_FIELD); coll.createIndex(indexKeys, indexOptions);
/** * Create index on billing collection. * * @param indexName the name of index. * @param index the index options. */ private void createBillingIndexes(String indexName, Bson index) { MongoCollection<Document> collection = database.getCollection(MongoConstants.COLLECTION_BILLING); IndexOptions options = new IndexOptions().name(MongoConstants.COLLECTION_BILLING + indexName); try { collection .createIndex(index, options); } catch (Exception e) { LOGGER.warn("Cannot create index {} on collection {}. {}", options.getName(), MongoConstants.COLLECTION_BILLING, e.getLocalizedMessage(), e); } }
IndexOptions options = new IndexOptions(); options.background(true); BasicDBObject weights = new BasicDBObject(); weights.put("lorem", 15); weights.put("_fulltext.text", 5); options.weights(weights); Document index = new Document(); index.put("$**", "text");
@Test public void testAddSparseIndexOnNonIdField() { collection.insertOne(json("someField: 'abc'")); assertThat(toArray(collection.listIndexes())).hasSize(1); collection.createIndex(new Document("someField", 1), new IndexOptions().sparse(true)); assertThat(toArray(collection.listIndexes())).hasSize(2); collection.insertOne(json("someField: 'abc'")); }
@Test public void testAddPartialIndexOnNonIdField() { collection.insertOne(json("someField: 'abc'")); assertThat(toArray(collection.listIndexes())).hasSize(1); collection.createIndex(new Document("someField", 1), new IndexOptions() .partialFilterExpression(json("someField: {$gt: 5}"))); assertThat(toArray(collection.listIndexes())).hasSize(2); collection.insertOne(json("someField: 'abc'")); }
/** * Makes an index to enforce unique constraint. * @return {@code this} indexer for chained invocation */ // safe unchecked: we expect I to be a self type @SuppressWarnings("unchecked") public final I unique() { options.unique(true); return (I) this; }
/** * Configures name for an index, that is otherwise will be auto-named by index fields. * @param indexName explicitly provided index name * @return {@code this} indexer for chained invocation */ // safe unchecked: we expect I to be a self type @SuppressWarnings("unchecked") public final I named(String indexName) { options.name(indexName); return (I) this; }
/** * Configures and TTL for an index. Creates an index on a time field, and document will be * removed when TTL will expire. * <p> * <em>Note: Care should be taken to configure TTL only on single time instant field</em> * @param timeToLiveSeconds time to live for an object, non-zero time in seconds required. * @return {@code this} indexer for chained invocation */ // safe unchecked: we expect I to be a self type @SuppressWarnings("unchecked") public final I expireAfterSeconds(int timeToLiveSeconds) { options.expireAfter((long) timeToLiveSeconds, TimeUnit.SECONDS); return (I) this; }