diff --git a/source/includes/usage-examples/index-code-examples.java b/source/includes/usage-examples/index-code-examples.java new file mode 100644 index 00000000..1b8958af --- /dev/null +++ b/source/includes/usage-examples/index-code-examples.java @@ -0,0 +1,117 @@ +import com.mongodb.ConnectionString; +import com.mongodb.MongoClientSettings; +import com.mongodb.ServerApi; +import com.mongodb.ServerApiVersion; + +import com.mongodb.client.model.ClusteredIndexOptions; +import com.mongodb.client.model.CreateCollectionOptions; +import com.mongodb.client.model.IndexOptions; +import com.mongodb.client.model.Indexes; +import com.mongodb.reactivestreams.client.*; +import org.bson.Document; +import org.reactivestreams.Publisher; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +public class IndexExamples { + public static void main(String[] args) { + // Replace the placeholder with your Atlas connection string + String uri = ""; + + // Construct a ServerApi instance using the ServerApi.builder() method + ServerApi serverApi = ServerApi.builder() + .version(ServerApiVersion.V1) + .build(); + + MongoClientSettings settings = MongoClientSettings.builder() + .applyConnectionString(new ConnectionString(uri)) + .serverApi(serverApi) + .build(); + + // Create a new client and connect to the server + try (MongoClient mongoClient = MongoClients.create(settings)) { + MongoDatabase database = mongoClient.getDatabase("sample_mflix"); + MongoCollection collection = database.getCollection("movies"); + + // start-single-field + Publisher publisher = collection.createIndex(Indexes.ascending("")); + Mono.from(publisher).block(); + // end-single-field + + // start-compound + Publisher publisher = collection.createIndex(Indexes.ascending("", "")); + Mono.from(publisher).block(); + // end-compound + + // start-multikey + Publisher publisher = collection.createIndex(Indexes.ascending("")); + Mono.from(publisher).block(); + // end-multikey + + // start-search-create + Document index = new Document("mappings", new Document("dynamic", true)); + Publisher publisher = collection.createSearchIndex("", index); + Mono.from(publisher).block(); + // end-search-create + + // start-search-list + ListSearchIndexesPublisher listIndexesPublisher = collection.listSearchIndexes(); + + Flux.from(listIndexesPublisher) + .doOnNext(System.out::println) + .blockLast(); + // end-search-list + + // start-search-update + Document newIndex = new Document("mappings", new Document("dynamic", true)); + Publisher publisher = collection.updateSearchIndex("", newIndex); + Mono.from(publisher).block(); + // end-search-update + + // start-search-delete + Publisher publisher = collection.dropIndex(""); + Mono.from(publisher).block(); + // end-search-delete + + // start-text + Publisher publisher = collection.createIndex(Indexes.text("")); + Mono.from(publisher).block(); + // end-text + + // start-geo + Publisher publisher = collection.createIndex(Indexes.geo2dsphere("")); + Mono.from(publisher).block(); + // end-geo + + // start-unique + IndexOptions indexOptions = new IndexOptions().unique(true); + Publisher publisher = collection.createIndex(Indexes.ascending(""), indexOptions); + Mono.from(publisher).block(); + // end-unique + + // start-wildcard + Publisher publisher = collection.createIndex(Indexes.ascending("$**")); + Mono.from(publisher).block(); + // end-wildcard + + // start-clustered + ClusteredIndexOptions clusteredIndexOptions = new ClusteredIndexOptions( + Indexes.ascending("_id"), + true + ); + + CreateCollectionOptions createCollectionOptions= new CreateCollectionOptions() + .clusteredIndexOptions(clusteredIndexOptions); + + Publisher clusteredCollection = database.createCollection("", + createCollectionOptions); + Mono.from(clusteredCollection).block(); + // end-clustered + + // start-remove + Publisher publisher = collection.dropIndex(""); + Mono.from(publisher).block(); + // end-remove + } + } +} \ No newline at end of file diff --git a/source/includes/usage-examples/sample-index-app-intro.rst b/source/includes/usage-examples/sample-index-app-intro.rst new file mode 100644 index 00000000..8adf19b3 --- /dev/null +++ b/source/includes/usage-examples/sample-index-app-intro.rst @@ -0,0 +1,11 @@ +You can use the following sample application to test the code examples on this +page. To use the sample application, perform the following steps: + +1. Create a new Java project in your IDE. +#. Install the {+driver-short+} in your Java project. +#. Install the `Project Reactor library + `__ in your + Java project. +#. Copy the following code and paste it into a new Java file named ``IndexApp.java``. +#. Copy a code example from this page and paste it on the specified lines in the + file. \ No newline at end of file diff --git a/source/includes/usage-examples/sample-index-application.java b/source/includes/usage-examples/sample-index-application.java new file mode 100644 index 00000000..75177265 --- /dev/null +++ b/source/includes/usage-examples/sample-index-application.java @@ -0,0 +1,41 @@ +import com.mongodb.ConnectionString; +import com.mongodb.MongoClientSettings; +import com.mongodb.ServerApi; +import com.mongodb.ServerApiVersion; + +import com.mongodb.client.model.ClusteredIndexOptions; +import com.mongodb.client.model.CreateCollectionOptions; +import com.mongodb.client.model.IndexOptions; +import com.mongodb.client.model.Indexes; +import com.mongodb.reactivestreams.client.*; +import org.bson.Document; +import org.reactivestreams.Publisher; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +public class IndexApp { + public static void main(String[] args) { + // Replace the placeholder with your Atlas connection string + String uri = ""; + + // Construct a ServerApi instance using the ServerApi.builder() method + ServerApi serverApi = ServerApi.builder() + .version(ServerApiVersion.V1) + .build(); + + MongoClientSettings settings = MongoClientSettings.builder() + .applyConnectionString(new ConnectionString(uri)) + .serverApi(serverApi) + .build(); + + // Create a new client and connect to the server + try (MongoClient mongoClient = MongoClients.create(settings)) { + MongoDatabase database = mongoClient.getDatabase(""); + MongoCollection collection = database.getCollection(""); + + // Start example code here + + // End example code here + } + } +} \ No newline at end of file diff --git a/source/indexes.txt b/source/indexes.txt index 2c76d4fa..dda9ca86 100644 --- a/source/indexes.txt +++ b/source/indexes.txt @@ -1,249 +1,278 @@ .. _java-rs-indexes: -============== -Create Indexes -============== - -.. facet:: - :name: genre - :values: reference - -.. meta:: - :keywords: code example, optimize, covered query +================================= +Optimize Queries by Using Indexes +================================= .. contents:: On this page :local: :backlinks: none - :depth: 1 + :depth: 2 :class: singlecol -Indexes support the efficient execution of queries in MongoDB. To -create an index on a field or fields, pass an index specification -document to the ``MongoCollection.createIndex()`` method. - -The {+driver-short+} provides the ``Indexes`` class that includes -static factory methods to create index specification documents for the -various MongoDB index key types. To learn more about index types, see -:manual:`Indexes ` in the Server manual. - -.. note:: - - MongoDB only creates an index if an index of the same specification - does not already exist. - -Prerequisites -------------- - -You must include the following import statements in your program to run the -code examples in this guide: - -.. code-block:: java - - import com.mongodb.reactivestreams.client.MongoClient; - import com.mongodb.reactivestreams.client.MongoClients; - import com.mongodb.reactivestreams.client.MongoDatabase; - import com.mongodb.reactivestreams.client.MongoCollection; - import org.bson.Document; +.. facet:: + :name: genre + :values: reference + +.. meta:: + :description: Learn how to use indexes by using the MongoDB Java Reactive Streams driver. + :keywords: query, optimization, efficiency, usage example, code example - import com.mongodb.client.model.Indexes; - import com.mongodb.client.model.IndexOptions; - import com.mongodb.client.model.Filters; +Overview +-------- -.. include:: /includes/subscriber-note.rst +On this page, you can see copyable code examples that show how to manage different +types of indexes by using the {+driver-short+}. -Connect to a MongoDB Deployment -------------------------------- +.. .. tip:: -.. include:: /includes/connect-section.rst +.. To learn more about working with indexes, see the :ref:`java-rs-work-with-indexes` +.. guide. To learn more about any of the indexes shown on this page, see the link +.. provided in each section. -Ascending Index ---------------- +To use an example from this page, copy the code example into the +:ref:`sample application ` or your own application. +Be sure to replace all placeholders in the code examples, such as ````, with +the relevant values for your MongoDB deployment. -To create a specification for an ascending index, use the -``Indexes.ascending()`` static helper method. +Project Reactor Implementation +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Single Ascending Index -~~~~~~~~~~~~~~~~~~~~~~ +This guide uses the {+pr+} library to consume ``Publisher`` instances returned +by the {+driver-short+} methods. To learn more about the {+pr+} library +and how to use it, see `Getting Started `__ +in the Reactor documentation. -The following example creates an ascending index on the ``name`` field: +There are also other ways to consume ``Publisher`` instances. You can use one of many alternative libraries such as +`RxJava `__ or call ``Publisher.subscribe()`` directly and pass your own +implementation of a ``Subscriber``. -.. code-block:: java +This guide uses the ``Mono.block()`` method from Reactor to subscribe to a ``Publisher`` and block the current +thread until the ``Publisher`` reaches its terminal state. To learn more about the Reactive Streams initiative, see `Reactive Streams `__. - collection.createIndex(Indexes.ascending("name")) - .subscribe(new PrintToStringSubscriber()); +.. important:: Publishers Returned are Cold -Compound Ascending Index -~~~~~~~~~~~~~~~~~~~~~~~~ + All ``Publisher`` instances returned by the {+driver-short+} methods are cold, + which means that the corresponding operation does not happen unless you + subscribe to the returned ``Publisher``. We recommend only subscribing to + the returned ``Publisher`` once, because subscribing more than once can lead + to errors. -The following example creates an ascending compound index on the -``stars`` field and the ``name`` field: +Sample Application +~~~~~~~~~~~~~~~~~~ -.. code-block:: java +.. _java-rs-index-sample: - collection.createIndex(Indexes.ascending("stars", "name")) - .subscribe(new PrintToStringSubscriber()); +.. include:: /includes/usage-examples/sample-index-app-intro.rst -To view an alternative way to create a compound index, see the :ref:`Compound -Indexes ` section. +.. literalinclude:: /includes/usage-examples/sample-index-application.java + :language: java + :copyable: + :linenos: + :emphasize-lines: 36-38 -Descending Index ----------------- +Single Field Index +------------------ -To create a specification of a descending index, use the -``Indexes.descending()`` static helper method. +The following example creates an ascending index on the specified field: -Single Descending Key Index -~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.. literalinclude:: /includes/usage-examples/index-code-examples.java + :start-after: start-single-field + :end-before: end-single-field + :language: java + :copyable: + :dedent: -The following example creates a descending index on the ``stars`` field: +.. TODO: To learn more about single field indexes, see the :ref:`java-rs-single-field-index` guide. -.. code-block:: java +Compound Index +-------------- - collection.createIndex(Indexes.descending("stars")) - .subscribe(new PrintToStringSubscriber()); +The following example creates a compound index on the specified fields: -Compound Descending Key Index -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.. literalinclude:: /includes/usage-examples/index-code-examples.java + :start-after: start-compound + :end-before: end-compound + :language: java + :copyable: + :dedent: -The following example creates a descending compound index on the -``stars`` field and the ``name`` field: +.. TODO: To learn more about compound indexes, see the :ref:`java-rs-compound-index` +.. guide. -.. code-block:: java +Multikey Index +-------------- - collection.createIndex(Indexes.descending("stars", "name")) - .subscribe(new PrintToStringSubscriber()); +The following example creates a multikey index on the specified array-valued field: -To view an alternative way to create a compound index, see the :ref:`Compound -Indexes ` section. +.. literalinclude:: /includes/usage-examples/index-code-examples.java + :start-after: start-multikey + :end-before: end-multikey + :language: java + :copyable: + :dedent: -.. _javars-compound-indexes: +.. TODO To learn more about multikey indexes, see the :ref:`java-rs-multikey-index` +.. guide. -Compound Indexes +Geospatial Index ---------------- -To create a specification for a compound index, use the -``Indexes.compoundIndex()`` static helper method. +The following example creates a ``2dsphere`` index on the specified field that contains +GeoJSON objects: -.. note:: +.. literalinclude:: /includes/usage-examples/index-code-examples.java + :start-after: start-geo + :end-before: end-geo + :language: java + :copyable: + :dedent: - To create a specification for a compound index where all the keys are - ascending, you can use the ``ascending()`` method. To create a - specification for a compound index where all the keys are descending, - you can use the ``descending()`` method. +.. TODO: To learn more about geospatial indexes, see the :ref:`java-rs-geospatial-index` +.. guide. -The following example creates a compound index on the ``stars`` field -in descending order and the ``name`` field in ascending order: +Unique Index +------------ -.. code-block:: java +The following example creates a unique index on the specified field: - collection.createIndex( - Indexes.compoundIndex(Indexes.descending("stars"), - Indexes.ascending("name")) - ).subscribe(new PrintToStringSubscriber()); +.. literalinclude:: /includes/usage-examples/index-code-examples.java + :start-after: start-unique + :end-before: end-unique + :language: java + :copyable: + :dedent: -Text Indexes ------------- +.. TODO: To learn more about unique indexes, see the :ref:`java-rs-unique-index` +.. guide. -MongoDB provides text indexes to support text search of string -content. Text indexes can include any field whose value is a string or -an array of string elements. To create a specification for a text -index, use the ``Indexes.text()`` static helper method. +Wildcard Index +-------------- -The following example creates a text index on the ``name`` field: +The following example creates a wildcard index in the specified collection: -.. code-block:: java +.. literalinclude:: /includes/usage-examples/index-code-examples.java + :start-after: start-wildcard + :end-before: end-wildcard + :language: java + :copyable: + :dedent: - collection.createIndex(Indexes.text("name")) - .subscribe(new PrintToStringSubscriber()); +.. TODO: To learn more about wildcard indexes, see the :ref:`java-rs-wildcard-index` +.. guide. -Hashed Index ------------- - -To create a specification for a hashed index index, use the -``Indexes.hashed()`` static helper method. +Clustered Index +--------------- -The following example creates a hashed index on the ``_id`` field: +The following example creates a new collection with a clustered index on the ``_id`` +field: -.. code-block:: java +.. literalinclude:: /includes/usage-examples/index-code-examples.java + :start-after: start-clustered + :end-before: end-clustered + :language: java + :copyable: + :dedent: - collection.createIndex(Indexes.hashed("_id")) - .subscribe(new PrintToStringSubscriber()); +.. TODO: To learn more about wildcard indexes, see the :ref:`java-rs-clustered-index` +.. guide. -Geospatial Indexes ------------------- +Atlas Search Index Management +----------------------------- -To support geospatial queries, MongoDB supports various geospatial +The following sections contain code examples that describe how to manage Atlas Search indexes. -2dsphere -~~~~~~~~ +.. TODO: To learn more about Atlas Search indexes, see the :ref:`java-rs-atlas-search-index` +.. guide. -To create a specification for a ``2dsphere`` index, use the -``Indexes.geo2dsphere()`` static helper method. +Create Search Index +~~~~~~~~~~~~~~~~~~~ -The following example creates a ``2dsphere`` index on the -``contact.location`` field: +The following example creates an Atlas Search index on the specified field: -.. code-block:: java +.. literalinclude:: /includes/usage-examples/index-code-examples.java + :start-after: start-search-create + :end-before: end-search-create + :language: java + :copyable: + :dedent: - collection.createIndex(Indexes.geo2dsphere("contact.location")) - .subscribe(new PrintToStringSubscriber()); +.. TODO: To learn more about creating search indexes, see the :ref:`java-rs-atlas-search-index-create` +.. guide. -IndexOptions ------------- +List Search Indexes +~~~~~~~~~~~~~~~~~~~ -In addition to the index specification document, the -``createIndex()`` method can take an index options document, that -directs the driver to create unique indexes or partial indexes. +The following example prints a list of Atlas Search indexes in the specified collection: -The driver provides the ``IndexOptions`` class to specify various -index options. +.. literalinclude:: /includes/usage-examples/index-code-examples.java + :start-after: start-search-list + :end-before: end-search-list + :language: java + :copyable: + :dedent: -Add the following import statement to your code to create an -``IndexOptions`` instance. +.. TODO: To learn more about listing search indexes, see the :ref:`java-rs-atlas-search-index-list` +.. guide. -.. code-block:: java +Update Search Indexes +~~~~~~~~~~~~~~~~~~~~~ - import com.mongodb.client.model.IndexOptions; +The following example updates an existing Atlas Search index with the specified +new index definition: -Unique Index -~~~~~~~~~~~~ +.. literalinclude:: /includes/usage-examples/index-code-examples.java + :start-after: start-search-update + :end-before: end-search-update + :language: java + :copyable: + :dedent: -The following code specifies the ``unique(true)`` option to create a -unique index on the ``name`` and ``stars`` fields: +.. TODO: To learn more about updating search indexes, see the :ref:`java-rs-atlas-search-index-update` +.. guide. -.. code-block:: java +Delete Search Indexes +~~~~~~~~~~~~~~~~~~~~~ - IndexOptions indexOptions = new IndexOptions().unique(true); - collection.createIndex(Indexes.ascending("name", "stars"), indexOptions) - .subscribe(new PrintToStringSubscriber()); +The following example deletes an Atlas Search index with the specified name: -Partial Index -~~~~~~~~~~~~~ +.. literalinclude:: /includes/usage-examples/index-code-examples.java + :start-after: start-search-delete + :end-before: end-search-delete + :language: java + :copyable: + :dedent: -To create a partial index, include the ``partialFilterExpression`` index -option. +.. TODO: To learn more about deleting search indexes, see the :ref:`java-rs-atlas-search-index-drop` +.. guide. -The following example creates a partial index on documents in which the -value of the ``status`` field is ``"A"``. +Text Index +---------- -.. code-block:: java +The following example creates a text index on the specified string field: - IndexOptions partialFilterIndexOptions = new IndexOptions() - .partialFilterExpression(Filters.exists("contact.email")); - collection.createIndex( - Indexes.descending("name", "stars"), partialFilterIndexOptions) - .subscribe(new PrintToStringSubscriber()); +.. literalinclude:: /includes/usage-examples/index-code-examples.java + :start-after: start-text + :end-before: end-text + :language: java + :copyable: + :dedent: -Get a List of Indexes on a Collection -------------------------------------- +.. TODO: To learn more about text indexes, see the :ref:`java-rs-text-index` +.. guide. -Use the ``listIndexes()`` method to get a list of indexes. The following code -lists the indexes on the collection: +Delete an Index +--------------- -.. code-block:: java +The following example deletes an index with the specified name: - collection.listIndexes().subscribe(new PrintDocumentSubscriber()); +.. literalinclude:: /includes/usage-examples/index-code-examples.java + :start-after: start-remove + :end-before: end-remove + :language: java + :copyable: + :dedent: -To learn about other index options, see :manual:`Index Properties -` in the Server manual. +.. TODO: To learn more about removing indexes, see :ref:`java-rs-indexes-remove` +.. in the Work with Indexes guide. \ No newline at end of file