Skip to content

DOCSP-39685: Indexes landing page #75

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Sep 10, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
117 changes: 117 additions & 0 deletions source/includes/usage-examples/index-code-examples.java
Original file line number Diff line number Diff line change
@@ -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 = "<connection 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<Document> collection = database.getCollection("movies");

// start-single-field
Publisher<String> publisher = collection.createIndex(Indexes.ascending("<field name>"));
Mono.from(publisher).block();
// end-single-field

// start-compound
Publisher<String> publisher = collection.createIndex(Indexes.ascending("<field name 1>", "<field name 2>"));
Mono.from(publisher).block();
// end-compound

// start-multikey
Publisher<String> publisher = collection.createIndex(Indexes.ascending("<array field name>"));
Mono.from(publisher).block();
// end-multikey

// start-search-create
Document index = new Document("mappings", new Document("dynamic", true));
Publisher<String> publisher = collection.createSearchIndex("<index name>", index);
Mono.from(publisher).block();
// end-search-create

// start-search-list
ListSearchIndexesPublisher<Document> 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<Void> publisher = collection.updateSearchIndex("<index name>", newIndex);
Mono.from(publisher).block();
// end-search-update

// start-search-delete
Publisher<Void> publisher = collection.dropIndex("<index name>");
Mono.from(publisher).block();
// end-search-delete

// start-text
Publisher<String> publisher = collection.createIndex(Indexes.text("<field name>"));
Mono.from(publisher).block();
// end-text

// start-geo
Publisher<String> publisher = collection.createIndex(Indexes.geo2dsphere("<GeoJSON object field>"));
Mono.from(publisher).block();
// end-geo

// start-unique
IndexOptions indexOptions = new IndexOptions().unique(true);
Publisher<String> publisher = collection.createIndex(Indexes.ascending("<field name>"), indexOptions);
Mono.from(publisher).block();
// end-unique

// start-wildcard
Publisher<String> 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<Void> clusteredCollection = database.createCollection("<collection name>",
createCollectionOptions);
Mono.from(clusteredCollection).block();
// end-clustered

// start-remove
Publisher<Void> publisher = collection.dropIndex("<index name>");
Mono.from(publisher).block();
// end-remove
}
}
}
11 changes: 11 additions & 0 deletions source/includes/usage-examples/sample-index-app-intro.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
You can use the following sample application to test the code examples on this
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems out of place, given other examples in the documentation don't provide such information. Generally, they seem to provide a block about the examples using Project reactor.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can add the extra info about using Project reactor to be more in line with the Read/Write landing pages.

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
<https://projectreactor.io/docs/core/release/reference/#getting>`__ 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.
41 changes: 41 additions & 0 deletions source/includes/usage-examples/sample-index-application.java
Original file line number Diff line number Diff line change
@@ -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;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The imports here must be the same as in index-code-examples.java, otherwise some code from index-code-examples.java may not compile when copied in IndexOperations.

import reactor.core.publisher.Mono;

public class IndexApp {
public static void main(String[] args) {
// Replace the placeholder with your Atlas connection string
String uri = "<connection 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("<database name>");
MongoCollection<Document> collection = database.getCollection("<collection name>");

// Start example code here

// End example code here
}
}
}
367 changes: 198 additions & 169 deletions source/indexes.txt
Original file line number Diff line number Diff line change
@@ -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 </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 <java-rs-index-sample>` or your own application.
Be sure to replace all placeholders in the code examples, such as ``<connection string URI>``, 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 <https://projectreactor.io/docs/core/release/reference/#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 <https://github.com/ReactiveX/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 <https://www.reactive-streams.org/>`__.

collection.createIndex(Indexes.ascending("name"))
.subscribe(new PrintToStringSubscriber<String>());
.. 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<String>());
.. include:: /includes/usage-examples/sample-index-app-intro.rst

To view an alternative way to create a compound index, see the :ref:`Compound
Indexes <javars-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<String>());
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<String>());
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 <javars-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<String>());
.. 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<String>());
.. 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<String>());
.. 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<String>());
.. 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<String>());
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<String>());
.. 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
</core/indexes/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.