ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Spring Data mongoDB(1.0.0 RC1 이상) 에서 collection에 index 추가 하기
    spring 2021. 3. 24. 14:32
    728x90
    반응형

    Spring Data mongoDB (1.0.0 RC1 이상) 에서 collection에 index 추가 하기

    코바 2012. 12. 10. 13:31

    Mongo DB에 인덱스를 추가하기 위해서는 직접 콘솔에서 명령을 쳐도 되지만 

    나중에 배포시 자동화를 위해 서버가 시작시 인덱스를 추가하기 위해 소스를 찾아보았다.

    현재 Spring Data mongoDB를 사용하고 있었으므로 그 부분 문서를 찾아보니 

    http://static.springsource.org/spring-data/data-document/docs/current/reference/html/#d0e2730

    mongoTemplate.ensureIndex(new Index().on("name",Order.ASCENDING), Person.class);

    이렇게 인덱스를 추가하라고 적혀 있었다.

     

    문제는 MongoTemplate에 아무리 찾아봐도 저 메소드가 존재하지 않는 것이었다.

    현재 사용하고 있는 Spring Data MongoDB 버전은 1.0.2 ( 찾아보니 1.0.0 RC1 이상에서 바뀐듯합니다. )

    어쩔 수 없이 소스를 다 훝어본 결과 

    index 추가하는 부분이 새롭게 클래스가 만들어져 있었다.

    어떤 버전 부터인지는 확인 못했지만 

     

    import org.springframework.data.mongodb.core.DefaultIndexOperations;

    import org.springframework.data.mongodb.core.IndexOperations;

    ...

    IndexOperations io = mongoTemplate.indexOps( "콜렉션명");

    // 동일 -> IndexOperations io = new DefaultIndexOperations(mongoTemplate, "콜렉션명");

    io.ensureIndex(new Index("username", Order.ASCENDING));

    이렇게 따로 인터페이스, 클래스로 빠져 있었다.

    혹시 나와 같은 사람이 있을지도 몰라서 이렇게 글을 남긴다.

     

    참고로 인덱스 생성 완성 코드는 

    // 콜렉션이 존재하지 않으면

    if ( !mongoTemplate.collectionExists("콜렉션명") ) {

    // 콜렉션을 추가하고  

    mongoTemplate.createCollection("콜렉션명");  

            IndexOperations io = mongoTemplate.indexOps( "콜렉션명");

    // 동일 -> IndexOperations io = new DefaultIndexOperations(mongoTemplate, "콜렉션명");

    // 필요한 인덱스를 추가

    io.ensureIndex(new Index("칼럼1", Order.ASCENDING).on("칼럼2", Order.ASCENDING));

    }

    이렇게 생성 하였다.



    출처: https://sbcoba.tistory.com/20 [홍이의 개발 노트]

    728x90
    반응형
Designed by Tistory.