Notice
Recent Posts
Recent Comments
Link
«   2025/06   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
관리 메뉴

Interstellar

[MongoDB] Text Index 본문

Data Science/MongoDB

[MongoDB] Text Index

HanGukJin 2017. 11. 14. 10:15

Text Index


Text Index 는 우리가 흔히 쓰는 검색엔진 검색처럼 제공된다


 몽고 DB를 이용해서 프로그램을 짤 때 text 관련 필드에 관해서 검색할 때는 정확하게 검색하고자 하는 text와 매칭이 되거나 regular expression 을 써야하지만 text index를 이용하면 쉽게 해결 할 수 있다.


※.

"Text Index 는 기존 Index와 달리 한개만 만들 수 있다"


Text Index 만들기


db.collection.createIndex( { 필드명 : "text" }, { name : 인덱스이름 } )

 * name을 이용해서 인덱스 이름을 넣으면 나중에 index를 관리할 때 편리하다


> db.reviews.createIndex( { comments : "text" } )

> db.enron.createIndex( { subject : "text" } )

 reviews collection 에서 comments ( enron collection 에서 subject ) 로 text index를 만든다.


Text Index 를 이용한 Search


db.collection.find( { $ text : { $search : "검색어" } } )


Example

 > db.reviews.find( { $text : { $search : "coffee" } } )

 위의 명령을 실행하면 text index가 만들어진 필드에 대해서 "coffee" 라는 단어가 포함 된 문서들을 검색한다.


OR 조건 검색

 > db.reviews.find( { $text : { $search : "bake coffee cake" } } )

 위의 명령대로 실행하면 검색할 때 bake, coffee, cake 중 하나라도 있으면 결과를 낸다


그외 명령어

대/소문자 구분

 > db.reviews.find( { $text: { $search : "coffee", $caseSensitive : false } } )


Phrase 검색 ( coffee shop 단어가 포함된 것을 검색 )

 > db.reviews.find( { $text: { $search : " \"coffee shop\" " } } )


AND 조건 검색

 > db.reviews.find( { $text: { $search : " \"coffee\" \"shop\" " } } )


textScore

 : 검색 결과로 등장한 문서들도 그 중요도가 다를 수 있다. 이 때 이용하는것이 textScore.


기존 검색에 textScore를 포함시켜서 검색한 후 textScore 순으로 sort 한다.

> db.reviews.find( { $text : {$search : "coffee"} },

{score : { $meta : "textScore" } } ).sort( { score : {$meta : "textScore" } } )

 

응용 : coffee 가 들어간 문서의 제목을 score 순으로 5개 출력

> db.reviews.find( { $text : {$search : "coffee"} },{score : { $meta : "textScore" }, subject : 1 } ).sort( { score : {$meta : "textScore" } } ).limit(5)