Docs Menu
Docs Home
/ / /
Java Reactive Streams 드라이버

인덱스를 사용하여 쿼리 최적화

이 페이지의 내용

  • 개요
  • 프로젝트 리액터 구현
  • 샘플 애플리케이션
  • 단일 필드 인덱스
  • 복합 인덱스
  • Multikey Index
  • 지리 공간적 인덱스
  • 고유 인덱스
  • 와일드카드 인덱스
  • 클러스터된 인덱스
  • Atlas 검색 인덱스 관리
  • Atlas Search 인덱스 만들기
  • 검색 인덱스 나열
  • 검색 인덱스 업데이트
  • Atlas Search 인덱스 삭제
  • Text Index
  • 인덱스 삭제

이 페이지에서는 Java Reactive Streams 드라이버를 사용하여 다양한 유형의 인덱스를 관리하는 방법을 보여주는 복사 가능한 코드 예제를 볼 수 있습니다.

이 페이지의 예제를 사용하려면 코드 예제를 샘플 애플리케이션 또는 자체 애플리케이션에 복사합니다. 코드 예제의 모든 자리 표시자(예: <connection string URI>)를 MongoDB 배포에 필요한 관련 값으로 바꿔야 합니다.

이 가이드에서는 Project Reactor 라이브러리를 Publisher 사용하여 Java Reactive Streams 드라이버 메서드에서 반환된 인스턴스를 사용합니다. Project Reactor 라이브러리 및 사용 방법에 대해 자세히 알아보려면 시작하기 를 참조하세요. Reactor 문서에서 확인 가능합니다.

인스턴스를 사용하는 다른 방법도 있습니다.Publisher RxJava 와 같은 많은 대체 라이브러리 중 하나를 사용할 수 있습니다. 또는 Publisher.subscribe() 를 직접 호출하여 의 구현을 전달할 수 있습니다.Subscriber

이 가이드에서는 Mono.block() Reactor의 메서드를 사용하여 Publisher 를 구독하고 가 Publisher 종료 상태에 도달할 때까지 현재 스레드를 차단합니다. Reactive Streams 이니셔티브에 대해 자세히 알아보려면 Reactive Streams를 참조하세요.

중요

반환된 게시자는 콜드

Java Reactive Streams 드라이버 메서드가 반환하는 모든 Publisher 인스턴스는 콜드 인스턴스이므로 반환된 Publisher 을(를) 구독하지 않는 한 해당 작업이 발생하지 않습니다. 반환된 Publisher 를 한 번만 구독하는 것이 좋습니다. 두 번 이상 구독하면 오류가 발생할 수 있기 때문입니다.

다음 샘플 애플리케이션을 사용하여 이 페이지의 코드 예제를 테스트할 수 있습니다. 샘플 애플리케이션을 사용하려면 다음 단계를 수행하세요.

  1. IDE에서 새 Java 프로젝트를 만듭니다.

  2. Java 프로젝트에 Java Reactive Streams 드라이버를 설치합니다.

  3. 프로젝트 리액터 라이브러리 설치 Java 프로젝트에서.

  4. 다음 코드를 복사하여 IndexApp.java 이라는 새 Java 파일에 붙여넣습니다.

  5. 이 페이지에서 코드 예제를 복사하여 파일의 지정된 줄에 붙여넣습니다.

1import com.mongodb.ConnectionString;
2import com.mongodb.MongoClientSettings;
3import com.mongodb.ServerApi;
4import com.mongodb.ServerApiVersion;
5
6import com.mongodb.client.model.ClusteredIndexOptions;
7import com.mongodb.client.model.CreateCollectionOptions;
8import com.mongodb.client.model.IndexOptions;
9import com.mongodb.client.model.Indexes;
10import com.mongodb.reactivestreams.client.*;
11import org.bson.Document;
12import org.reactivestreams.Publisher;
13import reactor.core.publisher.Flux;
14import reactor.core.publisher.Mono;
15
16public class IndexApp {
17 public static void main(String[] args) {
18 // Replace the placeholder with your Atlas connection string
19 String uri = "<connection string URI>";
20
21 // Construct a ServerApi instance using the ServerApi.builder() method
22 ServerApi serverApi = ServerApi.builder()
23 .version(ServerApiVersion.V1)
24 .build();
25
26 MongoClientSettings settings = MongoClientSettings.builder()
27 .applyConnectionString(new ConnectionString(uri))
28 .serverApi(serverApi)
29 .build();
30
31 // Create a new client and connect to the server
32 try (MongoClient mongoClient = MongoClients.create(settings)) {
33 MongoDatabase database = mongoClient.getDatabase("<database name>");
34 MongoCollection<Document> collection = database.getCollection("<collection name>");
35
36 // Start example code here
37
38 // End example code here
39 }
40 }
41}

다음 예에서는 지정된 필드에 오름차순 인덱스를 생성합니다.

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

다음 예에서는 지정된 필드에 복합 인덱스를 생성합니다.

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

다음 예제에서는 지정된 배열 값 필드에 멀티키 인덱스를 생성합니다.

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

다음 예에서는 GeoJSON 객체를 포함하는 지정된 필드에 2dsphere 인덱스를 생성합니다.

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

다음 예에서는 지정된 필드에 고유 인덱스를 생성합니다.

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

다음 예에서는 지정된 컬렉션에 와일드카드 인덱스를 생성합니다.

Publisher<String> publisher = collection.createIndex(Indexes.ascending("$**"));
Mono.from(publisher).block();

다음 예시에서는 _id 필드에 클러스터형 인덱스를 사용하여 새 컬렉션을 만듭니다.

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();

다음 섹션에는 Atlas Search 인덱스를 관리하는 방법을 설명하는 코드 예제가 포함되어 있습니다.

다음 예에서는 지정된 필드에 Atlas Search 인덱스를 생성합니다.

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

다음 예시에서는 지정된 컬렉션의 Atlas Search 인덱스 목록을 출력합니다.

ListSearchIndexesPublisher<Document> listIndexesPublisher = collection.listSearchIndexes();
Flux.from(listIndexesPublisher)
.doOnNext(System.out::println)
.blockLast();

다음 예에서는 지정된 새 인덱스 정의로 기존 Atlas Search 인덱스를 업데이트합니다.

Document newIndex = new Document("mappings", new Document("dynamic", true));
Publisher<Void> publisher = collection.updateSearchIndex("<index name>", newIndex);
Mono.from(publisher).block();

다음 예에서는 지정된 이름의 Atlas Search 인덱스를 삭제합니다.

Publisher<Void> publisher = collection.dropIndex("<index name>");
Mono.from(publisher).block();

다음 예에서는 지정된 문자열 필드에 텍스트 인덱스를 생성합니다.

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

다음 예에서는 지정된 이름의 인덱스를 삭제합니다.

Publisher<Void> publisher = collection.dropIndex("<index name>");
Mono.from(publisher).block();

돌아가기

데이터 변경 사항 모니터링