Text search
- MongoDB에서 text를 search할 때 사용
- keyword query는 exact match만 적용되거나 regular expression도 검색할때 제한이 있음
- text index를 만들면 text를 빠르게 찾을 수 있음
Text index
- 1개 이상의 field에 text index 생성 가능
> db.c.createIndex({a: "text", b: "text"}) -> a, b라는 field에 text 인덱스 생성
- 모든 text field에 인덱스 생성 가능
> db.c.createIndex({"$**": "text"}) -> 모든 field가 하나의 text index로 들어감
> db.c.createIndex({a:"text"},{name:"idx"}) -> index name 지정, name으로 삭제 가능
> db.c.dropIndex("idx")
- 하나의 collection에는 하나의 text 인덱스만 가능함
Text search operator
- text index를 가진 모든 field에서 text search 가능
> db.c.find({$text:{$search : "a b c"}}) -> a,b,c라는 string을 logical or로 찾음
- exact match가 필요할 때 : \"text\" 사용
> db.c.find({$text:{$search : "\"abc\""}})
- logical and 조건으로 찾을때
> db.c.find({$text:{$search : "\"abc\" "def\""}})
- 필요없는 조건을 빼고 찾을 때
> db.c.find({$text:{$search : "abc
-
def"}})
- case sensitive한 조건으로 찾을 때
> db.c.find({$text:{$search : "abc", $caseSensitive : true}}) -> default는 false
- 특정 language로 찾을 때
> db.c.find({$text:{$search : "abc", $language : en}})
- stemming words로 찾을 때
> db.c.find({$text:{$search : "apple"}}) 와 db.c.find({$text:{$search : "apples"}})는 동일한 결과를 가짐
- score field를 search 결과에 포함하기
> db.c.find({$text:{$search : "abc"}}, {score : {$meta : "textScore"}})
> db.c.find({$text:{$search : "abc"}}, {score : {$meta : "textScore"}}).sort({score : {$meta : "textScore"}}) -> search 결과를 score로 sort 가능
Text index field에 weight 주기
- text index는 순서가 의미 없이 동일 정보가 나옴 -> 더 중요한 field에 weight를 줘서 index를 생성할 수 있음
> db.c.createIndex({a: "text", b: "text"}, {weights : {a:3, b:2}}) -> a에 1.5배 더 weight를 줌
Compound index에서 text 사용
- compound index에서 text index를 사용 가능
> db.c.createIndex({a : 1, b: 'text'})
> db.c.createIndex({b: 'text', a : 1}) -> 두 결과는 다르게 나옴
MongoDB Index 종류
- B+-Tree : db.c.createIndex({A:1}) -> exact match, range
- hash table : db.c.createIndex({A:'hashed}) -> exact match
- GeoHash : db.c.createIndex({'coords':'2d'})
- inverted index : db.c.createIndex({'name':'text'})
'NoSQL' 카테고리의 다른 글
MongoDB - Aggregation (0) | 2023.08.09 |
---|---|
MongoDB - Geospatial data (0) | 2023.08.08 |
MongoDB - Indexing (0) | 2023.08.07 |
MongoDB - Querying (0) | 2023.08.07 |
MongoDB - Crud operations (0) | 2023.08.07 |