Typesense 컬렉션 다루기

Typesense 컬렉션 다루기

컬렉션은 Typesense에서 검색의 기본 단위예요. 도큐먼트를 넣기 전에 컬렉션을 만들고 필드 스키마를 정의해야 해요. 스키마는 나중에 검색·패싯·정렬에 어떻게 쓸지를 결정하므로, 처음부터 잘 설계하는 게 좋아요.

출처: https://typesense.org/docs/0.25.1/guides/create-a-collection.html

컬렉션 생성

컬렉션을 만들 때는 이름과 필드 목록을 지정해요. 각 필드에는 이름과 타입, 그리고 검색 옵션을 넣을 수 있어요.

curl 'http://localhost:8108/collections' \
  -H 'X-TYPESENSE-API-KEY: xyz' \
  -d '{
    "name": "books",
    "fields": [
      {"name": "title", "type": "string"},
      {"name": "authors", "type": "string[]"},
      {"name": "publication_year", "type": "int32", "sort": true},
      {"name": "ratings_count", "type": "int32"},
      {"name": "genres", "type": "string[]", "facet": true}
    ],
    "default_sorting_field": "ratings_count"
  }'

여기서 sort: true인 필드는 정렬에 쓸 수 있고, facet: true인 필드는 패싯 집계에 쓸 수 있어요. default_sorting_field는 아무 정렬 기준도 명시하지 않았을 때 쓰는 기본 정렬 필드예요.

필드 타입

Typesense의 필드 타입은 다양해요. 대표적으로 string(문자열), string[](문자열 배열), int32/int64(정수), float(실수), bool(불리언), geopoint(지리 좌표), object/object[](중첩 객체)가 있어요. auto 타입은 값이 들어올 때 타입을 자동 감지하도록 하는 옵션도 있어요.

컬렉션 조회·삭제

컬렉션 목록을 보거나 특정 컬렉션을 조회·삭제할 수 있어요.

curl 'http://localhost:8108/collections' \
  -H 'X-TYPESENSE-API-KEY: xyz'

curl 'http://localhost:8108/collections/books' \
  -H 'X-TYPESENSE-API-KEY: xyz'

도큐먼트 넣기

컬렉션에 도큐먼트를 넣을 때는 documents 엔드포인트로 JSON을 보내요. 배열로 여러 건을 한 번에 넣으면 벌크 인덱싱이 돼요.

curl 'http://localhost:8108/collections/books/documents' \
  -H 'X-TYPESENSE-API-KEY: xyz' \
  -d '[
    {"id": "1", "title": "The Hobbit", "publication_year": 1937},
    {"id": "2", "title": "Dune", "publication_year": 1965}
  ]'

더 알아보기