개요
이 페이지에서는 Java Reactive Streams 운전자 를 사용하여 다양한 유형의 인덱스를 관리 하는 방법을 보여주는 복사 가능한 코드 예제를 볼 수 있습니다.
이 페이지의 예제를 사용하려면 코드 예제를 샘플 애플리케이션 또는 자체 애플리케이션에 복사합니다. 코드 예제의 모든 자리 표시자(예: <connection string URI>
)를 MongoDB 배포에 필요한 관련 값으로 바꿔야 합니다.
프로젝트 리액터 구현
이 가이드 에서는 Project Reactor 라이브러리를 Publisher
사용하여 Java Reactive Streams 운전자 메서드에서 반환된 인스턴스를 사용합니다. 프로젝트 Reactor 라이브러리와 사용 방법에 대해 자세히 학습 Reactor 문서에서 시작하기 를 참조하세요.
Publisher
인스턴스를 사용하는 다른 방법도 있습니다. RxJava 와 같은 여러 대체 라이브러리 중 하나를 사용하거나 Publisher.subscribe()
를 직접 호출하여 Subscriber
의 구현 전달할 수 있습니다.
이 가이드 Reactor의 Mono.block()
메서드를 사용하여 Publisher
를 구독 하고 Publisher
가 종료 상태 에 도달할 때까지 현재 스레드를 차단 . Reactive Streams 이니셔티브에 대해 자세히 학습하려면 Reactive Streams를 참조하세요.
중요
반환된 게시자는 콜드
Java Reactive Streams 운전자 메서드가 반환하는 모든 Publisher
인스턴스는 콜드 인스턴스이므로 반환된 Publisher
을(를) 구독 하지 않는 한 해당 작업이 발생하지 않습니다. 반환된 Publisher
를 한 번만 구독 하는 것이 좋습니다. 두 번 이상 구독 하면 오류가 발생할 수 있기 때문입니다.
샘플 애플리케이션
다음 샘플 애플리케이션을 사용하여 이 페이지의 코드 예제를 테스트할 수 있습니다. 샘플 애플리케이션을 사용하려면 다음 단계를 수행하세요.
IDE에서 새 Java 프로젝트 를 만듭니다.
Java 프로젝트 에 Java Reactive Streams 운전자 를 설치합니다.
Java 프로젝트 에 Project Reactor 라이브러리를 설치합니다.
다음 코드를 복사하여
IndexApp.java
이라는 새 Java 파일 에 붙여넣습니다.이 페이지에서 코드 예제를 복사하여 파일의 지정된 줄에 붙여넣습니다.
1 import com.mongodb.ConnectionString; 2 import com.mongodb.MongoClientSettings; 3 import com.mongodb.ServerApi; 4 import com.mongodb.ServerApiVersion; 5 6 import com.mongodb.client.model.ClusteredIndexOptions; 7 import com.mongodb.client.model.CreateCollectionOptions; 8 import com.mongodb.client.model.IndexOptions; 9 import com.mongodb.client.model.Indexes; 10 import com.mongodb.reactivestreams.client.*; 11 import org.bson.Document; 12 import org.reactivestreams.Publisher; 13 import reactor.core.publisher.Flux; 14 import reactor.core.publisher.Mono; 15 16 public 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();
Multikey Index
다음 예시 에서는 지정된 배열 값 필드 에 멀티키 인덱스 를 생성합니다.
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 검색 인덱스 관리
다음 섹션에는 Atlas Search 인덱스를 관리 하는 방법을 설명하는 코드 예제가 포함되어 있습니다.
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 인덱스 삭제
다음 예시 에서는 지정된 이름의 Atlas Search 인덱스 를 삭제합니다.
Publisher<Void> publisher = collection.dropIndex("<index name>"); Mono.from(publisher).block();
Text Index
다음 예시 에서는 지정된 string 필드 에 텍스트 인덱스 를 생성합니다.
Publisher<String> publisher = collection.createIndex(Indexes.text("<field name>")); Mono.from(publisher).block();
인덱스 삭제
다음 예시 에서는 지정된 이름의 인덱스 를 삭제합니다.
Publisher<Void> publisher = collection.dropIndex("<index name>"); Mono.from(publisher).block();