Java Code Examples for com.mongodb.client.MongoCollection#createIndex()

The following examples show how to use com.mongodb.client.MongoCollection#createIndex() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MongoSession.java    From presto with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 2
Source File: MongoDocumentStorage.java    From lumongo with Apache License 2.0 6 votes vote down vote up
public MongoDocumentStorage(MongoClient mongoClient, String indexName, String dbName, String rawCollectionName, boolean sharded) {
	this.mongoClient = mongoClient;
	this.indexName = indexName;
	this.database = dbName;
	this.rawCollectionName = rawCollectionName;

	MongoDatabase storageDb = mongoClient.getDatabase(database);
	MongoCollection<Document> coll = storageDb.getCollection(ASSOCIATED_FILES + "." + FILES);
	coll.createIndex(new Document(ASSOCIATED_METADATA + "." + DOCUMENT_UNIQUE_ID_KEY, 1));
	coll.createIndex(new Document(ASSOCIATED_METADATA + "." + FILE_UNIQUE_ID_KEY, 1));

	if (sharded) {

		MongoDatabase adminDb = mongoClient.getDatabase(MongoConstants.StandardDBs.ADMIN);
		Document enableCommand = new Document();
		enableCommand.put(MongoConstants.Commands.ENABLE_SHARDING, database);
		adminDb.runCommand(enableCommand);

		shardCollection(storageDb, adminDb, rawCollectionName);
		shardCollection(storageDb, adminDb, ASSOCIATED_FILES + "." + CHUNKS);
	}
}
 
Example 3
Source File: NamedQueryRegistration.java    From epcis with Apache License 2.0 6 votes vote down vote up
private boolean addNamedEventQueryToDB(String name, String description, PollParameters p) {
	MongoCollection<BsonDocument> namedEventQueryCollection = Configuration.mongoDatabase.getCollection("NamedEventQuery",
			BsonDocument.class);
	MongoCollection<BsonDocument> eventDataCollection = Configuration.mongoDatabase.getCollection("EventData",
			BsonDocument.class);
	
	BsonDocument existingDoc = namedEventQueryCollection.find(new BsonDocument("name", new BsonString(name))).first();

	if (existingDoc == null) {
		BsonDocument bson = PollParameters.asBsonDocument(p);
		bson.put("name", new BsonString(name));
		bson.put("description", new BsonString(description));
		namedEventQueryCollection.insertOne(bson);
	} else {
		return false;
	}

	// Create Index with the given NamedEventQuery name and background option
	IndexOptions indexOptions = new IndexOptions().name(name).background(true);
	BsonDocument indexDocument = makeIndexObject(p);
	eventDataCollection.createIndex(indexDocument, indexOptions);
	
	Configuration.logger.log(Level.INFO, "NamedEventQuery: " + name + " is added to DB. ");
	return true;
}
 
Example 4
Source File: NamedQueryRegistration.java    From epcis with Apache License 2.0 6 votes vote down vote up
private boolean addNamedEventQueryToDB(String name, String description, PollParameters p) {
	MongoCollection<BsonDocument> namedEventQueryCollection = Configuration.mongoDatabase.getCollection("NamedEventQuery",
			BsonDocument.class);
	MongoCollection<BsonDocument> eventDataCollection = Configuration.mongoDatabase.getCollection("EventData",
			BsonDocument.class);
	
	BsonDocument existingDoc = namedEventQueryCollection.find(new BsonDocument("name", new BsonString(name))).first();

	if (existingDoc == null) {
		BsonDocument bson = PollParameters.asBsonDocument(p);
		bson.put("name", new BsonString(name));
		bson.put("description", new BsonString(description));
		namedEventQueryCollection.insertOne(bson);
	} else {
		return false;
	}

	// Create Index with the given NamedEventQuery name and background option
	IndexOptions indexOptions = new IndexOptions().name(name).background(true);
	BsonDocument indexDocument = makeIndexObject(p);
	eventDataCollection.createIndex(indexDocument, indexOptions);
	
	Configuration.logger.log(Level.INFO, "NamedEventQuery: " + name + " is added to DB. ");
	return true;
}
 
Example 5
Source File: ProfilingWriter.java    From mongodb-slow-operations-profiler with GNU Affero General Public License v3.0 6 votes vote down vote up
public ProfilingWriter(BlockingQueue<ProfilingEntry> jobQueue) {
    this.jobQueue = jobQueue;
    serverDto = ConfigReader.getCollectorServer();
    runningSince = new Date();

    final MongoDbAccessor mongo = getMongoDbAccessor();
    try {
        final MongoCollection<Document> profileCollection = getProfileCollection(mongo);

        IndexOptions indexOptions = new IndexOptions();
        indexOptions.background(true);
        LOG.info("Create index {ts:-1, lbl:1} in the background if it does not yet exists");
        profileCollection.createIndex(new BasicDBObject("ts",-1).append("lbl", 1), indexOptions);
        LOG.info("Create index {adr:1, db:1, ts:-1} in the background if it does not yet exists");
        profileCollection.createIndex(new BasicDBObject("adr",1).append("db",1).append("ts", -1), indexOptions);

        LOG.info("ProfilingWriter is ready at {}", serverDto.getHosts());

    } catch (MongoException e) {
        LOG.error("Exception while connecting to: {}", serverDto.getHosts(), e);
    }
}
 
Example 6
Source File: ProfilingWriter.java    From mongodb-slow-operations-profiler with GNU Affero General Public License v3.0 6 votes vote down vote up
private void init(MongoDbAccessor mongo) {
    LOG.info(">>> init");

    try {
        final MongoCollection<Document> profileCollection = getProfileCollection(mongo);

        IndexOptions indexOptions = new IndexOptions();
        indexOptions.background(true);
        LOG.info("Create index {ts:-1, lbl:1} in the background if it does not yet exists");
        profileCollection.createIndex(new BasicDBObject("ts",-1).append("lbl", 1), indexOptions);
        LOG.info("Create index {adr:1, db:1, ts:-1} in the background if it does not yet exists");
        profileCollection.createIndex(new BasicDBObject("adr",1).append("db",1).append("ts", -1), indexOptions);
        ApplicationStatusDto.addWebLog("ProfilingWriter is successfully connected to its collector database.");
    } catch (MongoException e) {
        LOG.error("Exception while connecting to: {}", serverDto.getHosts(), e);
        ApplicationStatusDto.addWebLog("ProfilingWriter could not connect to its collector database.");
    }
    
    LOG.info("<<< init");
}
 
Example 7
Source File: AggregateMergeTest.java    From mongodb-aggregate-query-support with Apache License 2.0 6 votes vote down vote up
@Test
public void mustNotOverwriteExistingDocuments() throws JsonProcessingException {
  String employeeCollection = RandomStringUtils.randomAlphabetic(10);
  String orgArchiveColl = RandomStringUtils.randomAlphabetic(10);
  List<Employee> originalEmployees = addEmployeeDocuments(employeeCollection, EMPLOYEE_DOCS);
  MongoCollection<Document> employeeColl = mongoTemplate.getCollection(employeeCollection);
  assertEquals(employeeColl.countDocuments(), originalEmployees.size());
  List<OrgArchiveEntry> orgArchiveEntries = addOrgArchiveEntries(orgArchiveColl, ORG_ARCHIVE_DOCS);
  MongoCollection<Document> orgArchiveCollection = mongoTemplate.getCollection(orgArchiveColl);
  assertEquals(orgArchiveCollection.countDocuments(), orgArchiveEntries.size());
  orgArchiveCollection.createIndex(BsonDocument.parse("{ \"fiscalYear\": 1, \"dept\": 1 }"), new IndexOptions().unique(true));
  zooEmployeeRepository.updateOrgArchiveInsertOnly(employeeCollection, orgArchiveColl);
  assertEquals(orgArchiveCollection.countDocuments(), orgArchiveEntries.size() + 2);
  Query query = new Query(Criteria.where("fiscalYear").is(2019));
  List<OrgArchiveEntry> newArchiveEntries = mongoTemplate.find(query, OrgArchiveEntry.class, orgArchiveColl);
  assertEquals(newArchiveEntries.size(), 2);
}
 
Example 8
Source File: MongoDocumentDb.java    From mdw with Apache License 2.0 5 votes vote down vote up
public static void createMongoDocIdIndex(String collectionName) {
    try {
        MongoDatabase mongoDb =  getMongoDb();
        if (mongoDb != null) {
            IndexOptions indexOptions = new IndexOptions().unique(true).background(true).name("document_id_1");
            MongoCollection<org.bson.Document> collection = mongoDb.getCollection(collectionName);
            String indexName = collection.createIndex(Indexes.ascending("document_id"), indexOptions);
            LoggerUtil.getStandardLogger().mdwDebug("Created Index : " + indexName + " on collection : " + collectionName);
            collectionDocIdIndexed.putIfAbsent(collectionName, true);
        }
    }
    catch (Exception e) {
        LoggerUtil.getStandardLogger().info("Failed to create index for 'document_id' on " + collectionName + " collection", e);
    }
}
 
Example 9
Source File: MongoCompensableLogger.java    From ByteTCC with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void createTransactionsGlobalTxKeyIndexIfNecessary() {
	String databaseName = CommonUtils.getApplication(this.endpoint).replaceAll("\\W", "_");
	MongoDatabase database = this.mongoClient.getDatabase(databaseName);
	MongoCollection<Document> transactions = database.getCollection(CONSTANTS_TB_TRANSACTIONS);
	ListIndexesIterable<Document> transactionIndexList = transactions.listIndexes();
	boolean transactionIndexExists = false;
	MongoCursor<Document> transactionCursor = null;
	try {
		transactionCursor = transactionIndexList.iterator();
		while (transactionIndexExists == false && transactionCursor.hasNext()) {
			Document document = transactionCursor.next();
			Boolean unique = document.getBoolean("unique");
			Document key = (Document) document.get("key");

			boolean globalExists = key.containsKey(CONSTANTS_FD_GLOBAL);
			boolean lengthEquals = key.size() == 1;
			transactionIndexExists = lengthEquals && globalExists;

			if (transactionIndexExists && (unique == null || unique == false)) {
				throw new IllegalStateException();
			}
		}
	} finally {
		IOUtils.closeQuietly(transactionCursor);
	}

	if (transactionIndexExists == false) {
		Document index = new Document(CONSTANTS_FD_GLOBAL, 1);
		transactions.createIndex(index, new IndexOptions().unique(true));
	}
}
 
Example 10
Source File: MongoCompensableLock.java    From ByteTCC with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void createLocksIndexIfNecessary() {
	String databaseName = CommonUtils.getApplication(this.endpoint).replaceAll("\\W", "_");
	MongoDatabase database = this.mongoClient.getDatabase(databaseName);
	MongoCollection<Document> locks = database.getCollection(CONSTANTS_TB_LOCKS);
	ListIndexesIterable<Document> lockIndexList = locks.listIndexes();
	boolean transactionIndexExists = false;
	MongoCursor<Document> lockCursor = null;
	try {
		lockCursor = lockIndexList.iterator();
		while (transactionIndexExists == false && lockCursor.hasNext()) {
			Document document = lockCursor.next();
			Boolean unique = document.getBoolean("unique");
			Document key = (Document) document.get("key");

			boolean globalExists = key.containsKey(CONSTANTS_FD_GLOBAL);
			boolean lengthEquals = key.size() == 1;
			transactionIndexExists = lengthEquals && globalExists;

			if (transactionIndexExists && (unique == null || unique == false)) {
				throw new IllegalStateException();
			}
		}
	} finally {
		IOUtils.closeQuietly(lockCursor);
	}

	if (transactionIndexExists == false) {
		Document index = new Document(CONSTANTS_FD_GLOBAL, 1);
		locks.createIndex(index, new IndexOptions().unique(true));
	}
}
 
Example 11
Source File: ResourceDAO.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void createResourceIndex() {					// added in 2017-03-13
	MongoCollection<Document> collection = context.getDatabaseManager()
			.getCollection(collectionName);
	
	collection.createIndex(new BasicDBObject("_uri", 1));
	collection.createIndex(new BasicDBObject("ri", 1));
	collection.createIndex(new BasicDBObject("pi", 1));
}
 
Example 12
Source File: ResourceDAO.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void createResourceIndex() {					// added in 2017-03-13
	MongoCollection<Document> collection = context.getDatabaseManager()
			.getCollection(collectionName);
	
	collection.createIndex(new BasicDBObject("_uri", 1));
	collection.createIndex(new BasicDBObject("ri", 1));
	collection.createIndex(new BasicDBObject("pi", 1));
}
 
Example 13
Source File: InsertOperation.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
private void insertIndexes(final MongoCollection<Document> collection, final List<Document> indexes) {
    for (final Document index : indexes) {

        final Document indexKeys = index.get("index", Document.class);

        if (index.containsKey("options")) {
            final Document indexOptions = index.get("options", Document.class);
            collection.createIndex(indexKeys, toIndexOptions(indexOptions));
        } else {
            collection.createIndex(indexKeys);
        }
    }
}
 
Example 14
Source File: ChangeEntryIndexDao.java    From mongobee with Apache License 2.0 5 votes vote down vote up
public void createRequiredUniqueIndex(MongoCollection<Document> collection) {
  collection.createIndex(new Document()
          .append(ChangeEntry.KEY_CHANGEID, 1)
          .append(ChangeEntry.KEY_AUTHOR, 1),
      new IndexOptions().unique(true)
  );
}
 
Example 15
Source File: ConfigService.java    From runelite with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Autowired
public ConfigService(
	MongoClient mongoClient,
	@Value("${mongo.database}") String databaseName
)
{

	MongoDatabase database = mongoClient.getDatabase(databaseName);
	MongoCollection<Document> collection = database.getCollection("config");
	this.mongoCollection = collection;

	// Create unique index on _userId
	IndexOptions indexOptions = new IndexOptions().unique(true);
	collection.createIndex(Indexes.ascending("_userId"), indexOptions);
}
 
Example 16
Source File: IndexHelper.java    From morphia with Apache License 2.0 5 votes vote down vote up
void createIndex(final MongoCollection collection, final MappedClass mc, final Index index) {
    Document keys = calculateKeys(mc, index);
    com.mongodb.client.model.IndexOptions indexOptions = convert(index.options());
    calculateWeights(index, indexOptions);

    collection.createIndex(keys, indexOptions);
}
 
Example 17
Source File: TextMongoDBStorageStrategy.java    From rya with Apache License 2.0 4 votes vote down vote up
@Override
public void createIndices(final MongoCollection<Document> coll){
    final Document indexDoc = new Document(TEXT, "text");
    coll.createIndex(indexDoc);
}
 
Example 18
Source File: TestMongoClient.java    From jframe with Apache License 2.0 4 votes vote down vote up
public void testDriverStatus() {
		CodecRegistry codecRegistry = CodecRegistries.fromRegistries(
				CodecRegistries.fromCodecs(new UuidCodec(
						UuidRepresentation.STANDARD)), MongoClient
						.getDefaultCodecRegistry());

		mongoClient.getDatabase("lech_rent").drop();
		MongoDatabase rent = mongoClient.getDatabase("lech_rent")
				.withCodecRegistry(codecRegistry);
		// rent.createCollection("driver_status", new CreateCollectionOptions()
		// .capped(true).sizeInBytes(0x100000));
		MongoCollection<Document> status = rent.getCollection("driver_status");
		status.deleteMany(Filters.eq("mobile", "18616020610"));
		if (status.count() == 0) {

		}
		status.createIndex(new Document("mobile", "text"));
		// status.createIndex(new Document("no", "text"));
		for (final Document index : status.listIndexes()) {
			System.out.println(index.toJson());
		}

		Document doc = new Document("loc",
				new Document("type", "Point").append("coordinates",
						Arrays.asList(-73.97, 40.77))).append("no", "dno")
				.append("usrImg", "/usr/driver.png")
				.append("mobile", "18616020610").append("status", 7)
				.append("car", new Document("no", "A00001"));
		status.insertOne(doc);
		// status.createIndex(keys);
		doc = status.find(Filters.eq("mobile", "18616020610")).first();

		System.out.println(doc.get("loc", Document.class).get("coordinates"));
		System.out.println(doc.get("loc", Document.class).get("coordinates",
				ArrayList.class));
		System.out.println(doc.get("car", Document.class));
		// System.out.println(doc.get("loc", Document.class));

//		UpdateResult updateResult = status.updateOne(Filters.eq("mobile",
//				"18616020610"), new Document("$set", new Document("car",
//				new Document("no", "A00002"))));
		doc = status.find(Filters.eq("mobile", "18616020610")).first();
		System.out.println(doc.get("car", Document.class));

		// updateResult = status.updateMany(Filters.lt("i", 100), new Document(
		// "$inc", new Document("i", 100)));
		// System.out.println(updateResult.getModifiedCount());
		// DeleteResult deleteResult = status.deleteOne(Filters.eq("i", 110));
		// System.out.println(deleteResult.getDeletedCount());

		// 2. Ordered bulk operation - order is guarenteed
		// status.bulkWrite(Arrays.asList(new InsertOneModel<>(new
		// Document("_id",
		// 4)), new InsertOneModel<>(new Document("_id", 5)),
		// new InsertOneModel<>(new Document("_id", 6)),
		// new UpdateOneModel<>(new Document("_id", 1), new Document(
		// "$set", new Document("x", 2))), new DeleteOneModel<>(
		// new Document("_id", 2)),
		// new ReplaceOneModel<>(new Document("_id", 3), new Document(
		// "_id", 3).append("x", 4))));

		// 2. Unordered bulk operation - no guarantee of order of operation
		// status.bulkWrite(Arrays.asList(new InsertOneModel<>(new
		// Document("_id",
		// 4)), new InsertOneModel<>(new Document("_id", 5)),
		// new InsertOneModel<>(new Document("_id", 6)),
		// new UpdateOneModel<>(new Document("_id", 1), new Document(
		// "$set", new Document("x", 2))), new DeleteOneModel<>(
		// new Document("_id", 2)),
		// new ReplaceOneModel<>(new Document("_id", 3), new Document(
		// "_id", 3).append("x", 4))), new BulkWriteOptions()
		// .ordered(false));

	}
 
Example 19
Source File: GeoMongoDBStorageStrategy.java    From rya with Apache License 2.0 4 votes vote down vote up
@Override
public void createIndices(final MongoCollection<Document> coll){
    coll.createIndex(new Document(GEO, "2dsphere"));
}
 
Example 20
Source File: MongoSchemaManager.java    From javers with Apache License 2.0 4 votes vote down vote up
public void ensureSchema(MongoDialect dialect) {
    //ensures collections and indexes
    MongoCollection<Document> snapshots = snapshotsCollection();
    snapshots.createIndex(new BasicDBObject(GLOBAL_ID_KEY, ASC));
    snapshots.createIndex(new BasicDBObject(GLOBAL_ID_VALUE_OBJECT, ASC));
    snapshots.createIndex(new BasicDBObject(GLOBAL_ID_ENTITY, ASC));
    snapshots.createIndex(new BasicDBObject(GLOBAL_ID_OWNER_ID_ENTITY, ASC));
    snapshots.createIndex(new BasicDBObject(CHANGED_PROPERTIES, ASC));

    if (dialect == MONGO_DB) {
        snapshots.createIndex(new BasicDBObject(COMMIT_PROPERTIES + ".key", ASC).append(COMMIT_PROPERTIES + ".value", ASC),
                new IndexOptions().name(COMMIT_PROPERTIES_INDEX_NAME));
    }
    else if (dialect == DOCUMENT_DB) {
        snapshots.createIndex(new BasicDBObject(COMMIT_PROPERTIES + ".key", ASC));
        snapshots.createIndex(new BasicDBObject(COMMIT_PROPERTIES + ".value", ASC));
    }

    headCollection();

    //schema migration script from JaVers 1.1 to 1.2
    Document doc = snapshots.find().first();
    if (doc != null) {
        Object stringCommitId = ((Map)doc.get("commitMetadata")).get("id");
        if (stringCommitId instanceof String) {
            logger.info("executing db migration script, from JaVers 1.1 to 1.2 ...");

            Document update = new Document("eval",
                    "function() { \n"+
                            "    db.jv_snapshots.find().forEach( \n"+
                            "      function(snapshot) { \n"+
                            "        snapshot.commitMetadata.id = Number(snapshot.commitMetadata.id); \n"+
                            "        db.jv_snapshots.save(snapshot); } \n" +
                            "    ); "+
                            "    return 'ok'; \n"+
                            "}"
            );

            Document ret = mongo.runCommand(update);
            logger.info("result: \n "+ ret.toJson());
        }
    }
}