From 8abb0987f2d16c72d811ed7f6fc2b83e2b457ecd Mon Sep 17 00:00:00 2001 From: Nikhiladiga Date: Sat, 25 Apr 2026 13:13:23 +0530 Subject: [PATCH 01/15] [FEAT]: initialize full-text search application with Spring Boot, Typesense integration, and automated synchronization scheduling --- README.md | 2 + .../.env.example | 26 ++ .../.gitattributes | 2 + .../.gitignore | 33 ++ .../.mvn/wrapper/maven-wrapper.properties | 3 + .../README.md | 241 ++++++++++++++ typesense-springboot-full-text-search/mvnw | 295 ++++++++++++++++++ .../mvnw.cmd | 189 +++++++++++ typesense-springboot-full-text-search/pom.xml | 127 ++++++++ .../FullTextSearchApplication.java | 25 ++ .../full_text_search/config/AsyncConfig.java | 22 ++ .../config/DatabaseInitializer.java | 55 ++++ .../config/TypesenseConfig.java | 40 +++ .../full_text_search/config/WebConfig.java | 18 ++ .../controller/BookController.java | 99 ++++++ .../controller/HealthController.java | 16 + .../controller/SearchController.java | 42 +++ .../controller/SyncController.java | 53 ++++ .../full_text_search/model/Book.java | 77 +++++ .../repository/BookRepository.java | 26 ++ .../scheduler/TypesenseSyncScheduler.java | 82 +++++ .../full_text_search/service/BookService.java | 70 +++++ .../service/TypesenseService.java | 266 ++++++++++++++++ .../src/main/resources/application.properties | 27 ++ .../FullTextSearchApplicationTests.java | 14 + 25 files changed, 1850 insertions(+) create mode 100644 typesense-springboot-full-text-search/.env.example create mode 100644 typesense-springboot-full-text-search/.gitattributes create mode 100644 typesense-springboot-full-text-search/.gitignore create mode 100644 typesense-springboot-full-text-search/.mvn/wrapper/maven-wrapper.properties create mode 100644 typesense-springboot-full-text-search/README.md create mode 100755 typesense-springboot-full-text-search/mvnw create mode 100644 typesense-springboot-full-text-search/mvnw.cmd create mode 100644 typesense-springboot-full-text-search/pom.xml create mode 100644 typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/FullTextSearchApplication.java create mode 100644 typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/config/AsyncConfig.java create mode 100644 typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/config/DatabaseInitializer.java create mode 100644 typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/config/TypesenseConfig.java create mode 100644 typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/config/WebConfig.java create mode 100644 typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/controller/BookController.java create mode 100644 typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/controller/HealthController.java create mode 100644 typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/controller/SearchController.java create mode 100644 typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/controller/SyncController.java create mode 100644 typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/model/Book.java create mode 100644 typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/repository/BookRepository.java create mode 100644 typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/scheduler/TypesenseSyncScheduler.java create mode 100644 typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/service/BookService.java create mode 100644 typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/service/TypesenseService.java create mode 100644 typesense-springboot-full-text-search/src/main/resources/application.properties create mode 100644 typesense-springboot-full-text-search/src/test/java/org/typesense/full_text_search/FullTextSearchApplicationTests.java diff --git a/README.md b/README.md index ed9054d..55e83e9 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ code-samples/ ├── typesense-qwik-js-search/ # Qwik + Typesense search implementation ├── typesense-react-native-search-bar/ # React Native + Typesense search implementation ├── typesense-solid-js-search/ # SolidJS + Typesense search implementation +├── typesense-springboot-full-text-search/ # Spring Boot + Typesense backend implementation ├── typesense-vanilla-js-search/ # Vanilla JS + Typesense search implementation └── README.md # You are here ``` @@ -32,6 +33,7 @@ code-samples/ | [typesense-qwik-js-search](./typesense-qwik-js-search) | Qwik | Resumable search bar with real-time search and modern UI | | [typesense-react-native-search-bar](./typesense-react-native-search-bar) | React Native | A mobile search bar with instant search capabilities | | [typesense-solid-js-search](./typesense-solid-js-search) | SolidJS | A modern search bar with instant search capabilities | +| [typesense-springboot-full-text-search](./typesense-springboot-full-text-search) | Spring Boot | Backend API with full-text search using Typesense | | [typesense-vanilla-js-search](./typesense-vanilla-js-search) | Vanilla JS | A modern search bar with instant search capabilities | ## Getting Started diff --git a/typesense-springboot-full-text-search/.env.example b/typesense-springboot-full-text-search/.env.example new file mode 100644 index 0000000..9463c54 --- /dev/null +++ b/typesense-springboot-full-text-search/.env.example @@ -0,0 +1,26 @@ +# Server Configuration +PORT=4000 + +# Database Configuration +DB_HOST=localhost +DB_PORT=5432 +DB_NAME=typesense_books +DB_USER=myuser +DB_PASSWORD=mypassword + +# JPA / Hibernate +HIBERNATE_DDL_AUTO=update + +# Typesense Configuration +TYPESENSE_HOST=localhost +TYPESENSE_PORT=8108 +TYPESENSE_PROTOCOL=http +TYPESENSE_API_KEY=xyz +TYPESENSE_COLLECTION_NAME=books +TYPESENSE_CONNECTION_TIMEOUT=2 + +# Sync Configuration +TYPESENSE_SYNC_INTERVAL=60000 +TYPESENSE_SYNC_BATCH_SIZE=1000 +TYPESENSE_SYNC_PAGE_SIZE=1000 +TYPESENSE_SYNC_ENABLE_SOFT_DELETE=true diff --git a/typesense-springboot-full-text-search/.gitattributes b/typesense-springboot-full-text-search/.gitattributes new file mode 100644 index 0000000..3b41682 --- /dev/null +++ b/typesense-springboot-full-text-search/.gitattributes @@ -0,0 +1,2 @@ +/mvnw text eol=lf +*.cmd text eol=crlf diff --git a/typesense-springboot-full-text-search/.gitignore b/typesense-springboot-full-text-search/.gitignore new file mode 100644 index 0000000..667aaef --- /dev/null +++ b/typesense-springboot-full-text-search/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/typesense-springboot-full-text-search/.mvn/wrapper/maven-wrapper.properties b/typesense-springboot-full-text-search/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..c595b00 --- /dev/null +++ b/typesense-springboot-full-text-search/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,3 @@ +wrapperVersion=3.3.4 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.14/apache-maven-3.9.14-bin.zip diff --git a/typesense-springboot-full-text-search/README.md b/typesense-springboot-full-text-search/README.md new file mode 100644 index 0000000..13aa5d2 --- /dev/null +++ b/typesense-springboot-full-text-search/README.md @@ -0,0 +1,241 @@ +# Spring Boot Full-Text Search with Typesense + +A production-ready RESTful search API built with Spring Boot, PostgreSQL, and Typesense. Features full-text search, CRUD operations, real-time async indexing, and scheduled background sync. + +## Tech Stack + +- Java 17+ +- Spring Boot 4.x +- PostgreSQL with Spring Data JPA +- Typesense +- Docker + +## Prerequisites + +- Java 17+ installed +- Maven 3.9+ +- Docker (for Typesense and PostgreSQL) + +## Quick Start + +### 1. Clone the repository + +```bash +git clone https://github.com/typesense/code-samples.git +cd typesense-springboot-full-text-search +``` + +### 2. Start Typesense and PostgreSQL + +```bash +# Start Typesense +docker run -d \ + -p 8108:8108 \ + -v typesense-data:/data \ + typesense/typesense:latest \ + --data-dir /data \ + --api-key=xyz \ + --enable-cors + +# Start PostgreSQL +docker run -d \ + -p 5432:5432 \ + -e POSTGRES_USER=postgres \ + -e POSTGRES_PASSWORD=password \ + -e POSTGRES_DB=typesense_books \ + -v postgres-data:/var/lib/postgresql/data \ + postgres:15 +``` + +### 3. Set up environment variables + +Copy the example file and adjust as needed: + +```bash +cp .env.example .env +``` + +Or export the variables directly: + +```bash +export DB_HOST=localhost +export DB_PORT=5432 +export DB_USER=postgres +export DB_PASSWORD=password +export DB_NAME=typesense_books +export TYPESENSE_HOST=localhost +export TYPESENSE_PORT=8108 +export TYPESENSE_PROTOCOL=http +export TYPESENSE_API_KEY=xyz +``` + +### 4. Project Structure + +```text +src/main/java/org/typesense/full_text_search/ +├── FullTextSearchApplication.java # Entry point (@EnableScheduling, @EnableAsync) +├── config/ +│ ├── TypesenseConfig.java # Typesense client bean +│ └── AsyncConfig.java # Thread pool for async Typesense operations +├── model/ +│ └── Book.java # JPA entity with soft delete support +├── repository/ +│ └── BookRepository.java # Spring Data JPA repository +├── service/ +│ ├── BookService.java # Book CRUD operations +│ └── TypesenseService.java # Typesense search, sync, collection management +├── scheduler/ +│ └── TypesenseSyncScheduler.java # @Scheduled periodic sync worker +└── controller/ + ├── BookController.java # CRUD endpoints for books + ├── SearchController.java # Search endpoint + └── SyncController.java # Manual sync + status endpoints +``` + +### 5. Start the development server + +```bash +./mvnw spring-boot:run +``` + +Open [http://localhost:4000](http://localhost:4000). + +### 6. API Endpoints + +#### Search + +```bash +GET /search?q= +``` + +Example: + +```bash +curl "http://localhost:4000/search?q=harry" +``` + +#### CRUD Operations + +**Create a book:** + +```bash +curl -X POST http://localhost:4000/books \ + -H "Content-Type: application/json" \ + -d '{ + "title": "The Go Programming Language", + "authors": ["Alan Donovan", "Brian Kernighan"], + "publicationYear": 2015, + "averageRating": 4.5, + "imageUrl": "https://example.com/image.jpg", + "ratingsCount": 1000 + }' +``` + +**Get a book:** + +```bash +GET /books/:id +``` + +**Get all books (paginated):** + +```bash +GET /books?page=1&page_size=100 +``` + +**Update a book:** + +```bash +PUT /books/:id +``` + +**Delete a book (soft delete):** + +```bash +DELETE /books/:id +``` + +#### Sync Operations + +**Trigger manual sync:** + +```bash +POST /sync +``` + +**Check sync status:** + +```bash +GET /sync/status +``` + +### 7. How It Works + +#### Architecture + +```plaintext +User Request + ↓ +Spring Boot API (CRUD) + ↓ +PostgreSQL (Source of Truth) + ↓ +Async Sync → Typesense (Search Index) + ↑ +@Scheduled Worker (Every 60s) +``` + +#### Sync Strategies + +##### 1. Startup Sync (Smart) + +On application startup (`ApplicationReadyEvent`), the scheduler checks whether the Typesense collection already has documents: + +- **Typesense is empty**: Seeds `lastSyncTime` to epoch and runs a full sync. +- **Typesense already has data**: Seeds `lastSyncTime` from `MAX(updated_at)` of the books table, then runs an incremental sync. + +##### 2. Real-time Sync (Async) + +- Triggered on: Create, Update, Delete operations +- Non-blocking: API responds immediately +- Runs in a dedicated thread pool (`typesenseAsyncExecutor`) +- If it fails, the background worker catches it within 60 seconds + +##### 3. Background Periodic Sync (`@Scheduled`) + +- Runs every 60 seconds (configurable via `typesense.sync.interval-ms`) +- Incremental: Only syncs books with `updated_at > lastSyncTime` +- Handles soft deletes: Removes deleted books from Typesense +- Uses upsert for both inserts and updates + +##### 4. Manual Sync + +- Endpoint: `POST /sync` +- On-demand sync trigger + +#### Configuration + +All sync parameters are configurable in `application.properties`: + +```properties +typesense.sync.interval-ms=60000 +typesense.sync.batch-size=1000 +typesense.sync.page-size=1000 +typesense.sync.enable-soft-delete=true +``` + +### 8. Deployment + +**Environment Variables for Production:** + +```env +DB_HOST=your-postgres-host.com +DB_USER=your-db-user +DB_PASSWORD=your-secure-password +DB_NAME=typesense_books +DB_PORT=5432 +TYPESENSE_HOST=xxx.typesense.net +TYPESENSE_PORT=443 +TYPESENSE_PROTOCOL=https +TYPESENSE_API_KEY=your-production-api-key +``` diff --git a/typesense-springboot-full-text-search/mvnw b/typesense-springboot-full-text-search/mvnw new file mode 100755 index 0000000..bd8896b --- /dev/null +++ b/typesense-springboot-full-text-search/mvnw @@ -0,0 +1,295 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.4 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +scriptDir="$(dirname "$0")" +scriptName="$(basename "$0")" + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +actualDistributionDir="" + +# First try the expected directory name (for regular distributions) +if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then + if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then + actualDistributionDir="$distributionUrlNameMain" + fi +fi + +# If not found, search for any directory with the Maven executable (for snapshots) +if [ -z "$actualDistributionDir" ]; then + # enable globbing to iterate over items + set +f + for dir in "$TMP_DOWNLOAD_DIR"/*; do + if [ -d "$dir" ]; then + if [ -f "$dir/bin/$MVN_CMD" ]; then + actualDistributionDir="$(basename "$dir")" + break + fi + fi + done + set -f +fi + +if [ -z "$actualDistributionDir" ]; then + verbose "Contents of $TMP_DOWNLOAD_DIR:" + verbose "$(ls -la "$TMP_DOWNLOAD_DIR")" + die "Could not find Maven distribution directory in extracted archive" +fi + +verbose "Found extracted Maven distribution directory: $actualDistributionDir" +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/typesense-springboot-full-text-search/mvnw.cmd b/typesense-springboot-full-text-search/mvnw.cmd new file mode 100644 index 0000000..92450f9 --- /dev/null +++ b/typesense-springboot-full-text-search/mvnw.cmd @@ -0,0 +1,189 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.4 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' + +$MAVEN_M2_PATH = "$HOME/.m2" +if ($env:MAVEN_USER_HOME) { + $MAVEN_M2_PATH = "$env:MAVEN_USER_HOME" +} + +if (-not (Test-Path -Path $MAVEN_M2_PATH)) { + New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null +} + +$MAVEN_WRAPPER_DISTS = $null +if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) { + $MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists" +} else { + $MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists" +} + +$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain" +$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +$actualDistributionDir = "" + +# First try the expected directory name (for regular distributions) +$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain" +$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD" +if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) { + $actualDistributionDir = $distributionUrlNameMain +} + +# If not found, search for any directory with the Maven executable (for snapshots) +if (!$actualDistributionDir) { + Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object { + $testPath = Join-Path $_.FullName "bin/$MVN_CMD" + if (Test-Path -Path $testPath -PathType Leaf) { + $actualDistributionDir = $_.Name + } + } +} + +if (!$actualDistributionDir) { + Write-Error "Could not find Maven distribution directory in extracted archive" +} + +Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir" +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/typesense-springboot-full-text-search/pom.xml b/typesense-springboot-full-text-search/pom.xml new file mode 100644 index 0000000..98c1710 --- /dev/null +++ b/typesense-springboot-full-text-search/pom.xml @@ -0,0 +1,127 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 4.0.5 + + + org.typesense + full-text-search + 0.0.1-SNAPSHOT + + + + + + + + + + + + + + + + + 17 + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-webmvc + + + + org.typesense + typesense-java + 1.3.0 + + + org.postgresql + postgresql + runtime + + + org.projectlombok + lombok + true + + + com.h2database + h2 + test + + + org.springframework.boot + spring-boot-starter-test + test + + + io.github.cdimascio + dotenv-java + 3.0.0 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + default-compile + compile + + compile + + + + + org.projectlombok + lombok + + + + + + default-testCompile + test-compile + + testCompile + + + + + org.projectlombok + lombok + + + + + + + + + + diff --git a/typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/FullTextSearchApplication.java b/typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/FullTextSearchApplication.java new file mode 100644 index 0000000..1a63fda --- /dev/null +++ b/typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/FullTextSearchApplication.java @@ -0,0 +1,25 @@ +package org.typesense.full_text_search; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.typesense.full_text_search.config.DatabaseInitializer; + +import io.github.cdimascio.dotenv.Dotenv; + +@SpringBootApplication +@EnableScheduling +@EnableAsync +public class FullTextSearchApplication { + + public static void main(String[] args) { + // Load .env variables into system properties for Spring Boot to use + Dotenv dotenv = Dotenv.configure().ignoreIfMissing().load(); + dotenv.entries().forEach(entry -> System.setProperty(entry.getKey(), entry.getValue())); + + DatabaseInitializer.ensureDatabaseExists(); + SpringApplication.run(FullTextSearchApplication.class, args); + } + +} diff --git a/typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/config/AsyncConfig.java b/typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/config/AsyncConfig.java new file mode 100644 index 0000000..e6b8ee7 --- /dev/null +++ b/typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/config/AsyncConfig.java @@ -0,0 +1,22 @@ +package org.typesense.full_text_search.config; + +import java.util.concurrent.Executor; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; + +@Configuration +public class AsyncConfig { + + @Bean(name = "typesenseAsyncExecutor") + public Executor typesenseAsyncExecutor() { + ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); + executor.setCorePoolSize(2); + executor.setMaxPoolSize(4); + executor.setQueueCapacity(100); + executor.setThreadNamePrefix("typesense-async-"); + executor.initialize(); + return executor; + } +} diff --git a/typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/config/DatabaseInitializer.java b/typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/config/DatabaseInitializer.java new file mode 100644 index 0000000..6a571cf --- /dev/null +++ b/typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/config/DatabaseInitializer.java @@ -0,0 +1,55 @@ +package org.typesense.full_text_search.config; + +import java.io.InputStream; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.Statement; +import java.util.Properties; + +public class DatabaseInitializer { + + private DatabaseInitializer() { + } + + public static void ensureDatabaseExists() { + Properties props = new Properties(); + try (InputStream is = DatabaseInitializer.class.getClassLoader() + .getResourceAsStream("application.properties")) { + if (is != null) { + props.load(is); + } + } catch (Exception e) { + System.err.println("Could not load application.properties: " + e.getMessage()); + return; + } + + String url = props.getProperty("spring.datasource.url"); + String username = props.getProperty("spring.datasource.username"); + String password = props.getProperty("spring.datasource.password"); + + if (url == null || !url.contains("postgresql")) return; + + String dbName = extractDatabaseName(url); + String baseUrl = url.substring(0, url.lastIndexOf('/')) + "/postgres"; + + try (Connection conn = DriverManager.getConnection(baseUrl, username, password); + Statement stmt = conn.createStatement()) { + + ResultSet rs = stmt.executeQuery( + "SELECT 1 FROM pg_database WHERE datname = '" + dbName + "'"); + + if (!rs.next()) { + stmt.execute("CREATE DATABASE " + dbName); + System.out.println("Database '" + dbName + "' created successfully"); + } + } catch (Exception e) { + System.err.println("Failed to create database '" + dbName + "': " + e.getMessage()); + } + } + + private static String extractDatabaseName(String url) { + String withoutParams = url.contains("?") ? url.substring(0, url.indexOf('?')) : url; + return withoutParams.substring(withoutParams.lastIndexOf('/') + 1); + } +} diff --git a/typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/config/TypesenseConfig.java b/typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/config/TypesenseConfig.java new file mode 100644 index 0000000..0a9db11 --- /dev/null +++ b/typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/config/TypesenseConfig.java @@ -0,0 +1,40 @@ +package org.typesense.full_text_search.config; + +import java.time.Duration; +import java.util.List; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.typesense.api.Client; +import org.typesense.resources.Node; + +@Configuration +public class TypesenseConfig { + + @Value("${typesense.protocol}") + private String protocol; + + @Value("${typesense.host}") + private String host; + + @Value("${typesense.port}") + private String port; + + @Value("${typesense.api-key}") + private String apiKey; + + @Value("${typesense.connection-timeout-seconds}") + private int connectionTimeoutSeconds; + + @Bean + public Client typesenseClient() { + Node node = new Node(protocol, host, port); + org.typesense.api.Configuration configuration = new org.typesense.api.Configuration( + List.of(node), + Duration.ofSeconds(connectionTimeoutSeconds), + apiKey + ); + return new Client(configuration); + } +} diff --git a/typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/config/WebConfig.java b/typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/config/WebConfig.java new file mode 100644 index 0000000..2f8d595 --- /dev/null +++ b/typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/config/WebConfig.java @@ -0,0 +1,18 @@ +package org.typesense.full_text_search.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.CorsRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +public class WebConfig implements WebMvcConfigurer { + + @Override + public void addCorsMappings(CorsRegistry registry) { + registry.addMapping("/**") + .allowedOrigins("*") + .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") + .allowedHeaders("Origin", "Content-Type", "Accept", "Authorization") + .exposedHeaders("Content-Length"); + } +} diff --git a/typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/controller/BookController.java b/typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/controller/BookController.java new file mode 100644 index 0000000..56f2225 --- /dev/null +++ b/typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/controller/BookController.java @@ -0,0 +1,99 @@ +package org.typesense.full_text_search.controller; + +import java.util.Map; + +import org.springframework.data.domain.Page; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.typesense.full_text_search.model.Book; +import org.typesense.full_text_search.service.BookService; +import org.typesense.full_text_search.service.TypesenseService; + +@RestController +@RequestMapping("/books") +public class BookController { + + private final BookService bookService; + private final TypesenseService typesenseService; + + public BookController(BookService bookService, TypesenseService typesenseService) { + this.bookService = bookService; + this.typesenseService = typesenseService; + } + + @PostMapping + public ResponseEntity> createBook(@RequestBody Book book) { + Book saved = bookService.save(book); + typesenseService.syncBookAsync(saved); + return ResponseEntity.status(HttpStatus.CREATED).body(Map.of( + "message", "Book created successfully", + "book", saved + )); + } + + @GetMapping("/{id}") + public ResponseEntity> getBook(@PathVariable Long id) { + return bookService.findById(id) + .map(book -> ResponseEntity.ok(Map.of("book", book))) + .orElse(ResponseEntity.status(HttpStatus.NOT_FOUND) + .body(Map.of("error", "Book not found"))); + } + + @GetMapping + public ResponseEntity> getAllBooks( + @RequestParam(defaultValue = "1") int page, + @RequestParam(name = "page_size", defaultValue = "100") int pageSize) { + + Page books = bookService.findAll(page, pageSize); + return ResponseEntity.ok(Map.of( + "count", books.getNumberOfElements(), + "total", books.getTotalElements(), + "page", page, + "page_size", pageSize, + "books", books.getContent() + )); + } + + @PutMapping("/{id}") + public ResponseEntity> updateBook(@PathVariable Long id, @RequestBody Book updates) { + return bookService.findById(id) + .map(existing -> { + if (updates.getTitle() != null) existing.setTitle(updates.getTitle()); + if (updates.getAuthors() != null) existing.setAuthors(updates.getAuthors()); + if (updates.getPublicationYear() != null) existing.setPublicationYear(updates.getPublicationYear()); + if (updates.getAverageRating() != null) existing.setAverageRating(updates.getAverageRating()); + if (updates.getImageUrl() != null) existing.setImageUrl(updates.getImageUrl()); + if (updates.getRatingsCount() != null) existing.setRatingsCount(updates.getRatingsCount()); + + Book saved = bookService.save(existing); + typesenseService.syncBookAsync(saved); + return ResponseEntity.ok(Map.of( + "message", "Book updated successfully", + "book", saved + )); + }) + .orElse(ResponseEntity.status(HttpStatus.NOT_FOUND) + .body(Map.of("error", "Book not found"))); + } + + @DeleteMapping("/{id}") + public ResponseEntity> deleteBook(@PathVariable Long id) { + return bookService.findById(id) + .map(book -> { + bookService.deleteById(id); + typesenseService.deleteBookAsync(id); + return ResponseEntity.ok(Map.of("message", "Book deleted successfully")); + }) + .orElse(ResponseEntity.status(HttpStatus.NOT_FOUND) + .body(Map.of("error", "Book not found"))); + } +} diff --git a/typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/controller/HealthController.java b/typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/controller/HealthController.java new file mode 100644 index 0000000..e6f001e --- /dev/null +++ b/typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/controller/HealthController.java @@ -0,0 +1,16 @@ +package org.typesense.full_text_search.controller; + +import java.util.Map; + +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class HealthController { + + @GetMapping("/ping") + public ResponseEntity> ping() { + return ResponseEntity.ok(Map.of("message", "pong")); + } +} diff --git a/typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/controller/SearchController.java b/typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/controller/SearchController.java new file mode 100644 index 0000000..51d5274 --- /dev/null +++ b/typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/controller/SearchController.java @@ -0,0 +1,42 @@ +package org.typesense.full_text_search.controller; + +import java.util.Map; + +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.typesense.full_text_search.service.TypesenseService; +import org.typesense.model.SearchResult; + +@RestController +public class SearchController { + + private final TypesenseService typesenseService; + + public SearchController(TypesenseService typesenseService) { + this.typesenseService = typesenseService; + } + + @GetMapping("/search") + public ResponseEntity> search(@RequestParam("q") String query) { + if (query == null || query.isBlank()) { + return ResponseEntity.badRequest().body(Map.of("error", "Search query parameter 'q' is required")); + } + + try { + SearchResult result = typesenseService.search(query); + return ResponseEntity.ok(Map.of( + "query", query, + "results", result.getHits() != null ? result.getHits() : java.util.List.of(), + "found", result.getFound() != null ? result.getFound() : 0, + "took", result.getSearchTimeMs() != null ? result.getSearchTimeMs() : 0, + "facet_counts", result.getFacetCounts() != null ? result.getFacetCounts() : java.util.List.of() + )); + } catch (Exception e) { + return ResponseEntity.internalServerError().body(Map.of( + "error", "Search failed: " + e.getMessage() + )); + } + } +} diff --git a/typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/controller/SyncController.java b/typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/controller/SyncController.java new file mode 100644 index 0000000..4f8d500 --- /dev/null +++ b/typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/controller/SyncController.java @@ -0,0 +1,53 @@ +package org.typesense.full_text_search.controller; + +import java.time.Instant; +import java.util.Map; + +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.typesense.full_text_search.service.TypesenseService; + +@RestController +@RequestMapping("/sync") +public class SyncController { + + private final TypesenseService typesenseService; + + public SyncController(TypesenseService typesenseService) { + this.typesenseService = typesenseService; + } + + @PostMapping + public ResponseEntity> triggerSync() { + Instant lastSyncTime = typesenseService.getLastSyncTime(); + + try { + Instant newSyncTime = typesenseService.syncBooksToTypesense(lastSyncTime); + int deletedCount = typesenseService.syncSoftDeletesToTypesense(lastSyncTime); + typesenseService.setLastSyncTime(newSyncTime); + + return ResponseEntity.ok(Map.of( + "message", "Sync completed", + "newSyncTime", newSyncTime.toString(), + "syncedAt", Instant.now().toString(), + "deletedBooks", deletedCount + )); + } catch (Exception e) { + return ResponseEntity.internalServerError().body(Map.of( + "error", "Sync failed", + "message", e.getMessage() + )); + } + } + + @GetMapping("/status") + public ResponseEntity> getSyncStatus() { + return ResponseEntity.ok(Map.of( + "lastSyncTime", typesenseService.getLastSyncTime().toString(), + "syncWorkerRunning", typesenseService.isSyncWorkerRunning() + )); + } +} diff --git a/typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/model/Book.java b/typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/model/Book.java new file mode 100644 index 0000000..e29247a --- /dev/null +++ b/typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/model/Book.java @@ -0,0 +1,77 @@ +package org.typesense.full_text_search.model; + +import java.time.Instant; +import java.util.List; + +import org.hibernate.annotations.SQLDelete; +import org.hibernate.annotations.SQLRestriction; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.PreUpdate; +import jakarta.persistence.Table; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@Entity +@Table(name = "books") +@SQLDelete(sql = "UPDATE books SET deleted_at = NOW(), updated_at = NOW() WHERE id = ?") +@SQLRestriction("deleted_at IS NULL") +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +public class Book { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String title; + + @Column(columnDefinition = "jsonb") + @org.hibernate.annotations.JdbcTypeCode(org.hibernate.type.SqlTypes.JSON) + private List authors; + + @Column(name = "publication_year") + private Integer publicationYear; + + @Column(name = "average_rating") + private Double averageRating; + + @Column(name = "image_url") + private String imageUrl; + + @Column(name = "ratings_count") + private Integer ratingsCount; + + @Column(name = "created_at", updatable = false) + private Instant createdAt; + + @Column(name = "updated_at") + private Instant updatedAt; + + @Column(name = "deleted_at") + private Instant deletedAt; + + @jakarta.persistence.PrePersist + protected void onCreate() { + Instant now = Instant.now(); + this.createdAt = now; + this.updatedAt = now; + } + + @PreUpdate + protected void onUpdate() { + this.updatedAt = Instant.now(); + } + + public String getTypesenseId() { + return "book_" + id; + } +} diff --git a/typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/repository/BookRepository.java b/typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/repository/BookRepository.java new file mode 100644 index 0000000..6fbe8f9 --- /dev/null +++ b/typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/repository/BookRepository.java @@ -0,0 +1,26 @@ +package org.typesense.full_text_search.repository; + +import java.time.Instant; +import java.util.List; +import java.util.Optional; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.typesense.full_text_search.model.Book; + +public interface BookRepository extends JpaRepository { + + Page findByUpdatedAtAfterOrderByUpdatedAtAsc(Instant since, Pageable pageable); + + long countByUpdatedAtAfter(Instant since); + + @Query("SELECT MAX(b.updatedAt) FROM Book b") + Optional findLatestUpdatedAt(); + + @Query(value = "SELECT * FROM books WHERE deleted_at IS NOT NULL AND updated_at > :since", + nativeQuery = true) + List findDeletedBooksSince(@Param("since") Instant since); +} diff --git a/typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/scheduler/TypesenseSyncScheduler.java b/typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/scheduler/TypesenseSyncScheduler.java new file mode 100644 index 0000000..6645d4e --- /dev/null +++ b/typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/scheduler/TypesenseSyncScheduler.java @@ -0,0 +1,82 @@ +package org.typesense.full_text_search.scheduler; + +import java.time.Instant; +import java.util.concurrent.atomic.AtomicBoolean; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.context.event.ApplicationReadyEvent; +import org.springframework.context.event.EventListener; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; +import org.typesense.full_text_search.service.BookService; +import org.typesense.full_text_search.service.TypesenseService; + +@Component +public class TypesenseSyncScheduler { + + private static final Logger log = LoggerFactory.getLogger(TypesenseSyncScheduler.class); + + private final TypesenseService typesenseService; + private final BookService bookService; + private final AtomicBoolean initialSyncDone = new AtomicBoolean(false); + + public TypesenseSyncScheduler(TypesenseService typesenseService, BookService bookService) { + this.typesenseService = typesenseService; + this.bookService = bookService; + } + + @EventListener(ApplicationReadyEvent.class) + public void onApplicationReady() { + try { + typesenseService.initializeCollection(); + } catch (Exception e) { + log.error("Failed to initialize Typesense collection: {}", e.getMessage()); + return; + } + + typesenseService.setSyncWorkerRunning(true); + + try { + long docCount = typesenseService.collectionDocumentCount(); + if (docCount > 0) { + bookService.findLatestUpdatedAt().ifPresent(latest -> { + typesenseService.setLastSyncTime(latest); + log.info("Typesense already populated, seeding sync time from DB: {}", latest); + }); + } else { + log.info("Typesense collection is empty, will run full sync"); + } + + Instant lastSyncTime = typesenseService.getLastSyncTime(); + Instant newSyncTime = typesenseService.syncBooksToTypesense(lastSyncTime); + typesenseService.setLastSyncTime(newSyncTime); + log.info("Initial sync completed at {}", newSyncTime); + } catch (Exception e) { + log.error("Initial sync failed: {}", e.getMessage()); + } + + initialSyncDone.set(true); + } + + @Scheduled(fixedDelayString = "${typesense.sync.interval-ms}") + public void periodicSync() { + if (!initialSyncDone.get()) return; + + log.info("Running periodic sync..."); + Instant lastSyncTime = typesenseService.getLastSyncTime(); + + try { + Instant newSyncTime = typesenseService.syncBooksToTypesense(lastSyncTime); + typesenseService.setLastSyncTime(newSyncTime); + } catch (Exception e) { + log.error("Periodic sync failed: {}", e.getMessage()); + } + + try { + typesenseService.syncSoftDeletesToTypesense(lastSyncTime); + } catch (Exception e) { + log.error("Soft delete sync failed: {}", e.getMessage()); + } + } +} diff --git a/typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/service/BookService.java b/typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/service/BookService.java new file mode 100644 index 0000000..80d36d8 --- /dev/null +++ b/typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/service/BookService.java @@ -0,0 +1,70 @@ +package org.typesense.full_text_search.service; + +import java.time.Instant; +import java.util.List; +import java.util.Optional; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Sort; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.typesense.full_text_search.model.Book; +import org.typesense.full_text_search.repository.BookRepository; + +@Service +public class BookService { + + private final BookRepository bookRepository; + + public BookService(BookRepository bookRepository) { + this.bookRepository = bookRepository; + } + + @Transactional + public Book save(Book book) { + return bookRepository.save(book); + } + + @Transactional(readOnly = true) + public Optional findById(Long id) { + return bookRepository.findById(id); + } + + @Transactional(readOnly = true) + public Page findAll(int page, int pageSize) { + return bookRepository.findAll( + PageRequest.of(page - 1, pageSize, Sort.by("id").ascending())); + } + + @Transactional(readOnly = true) + public long count() { + return bookRepository.count(); + } + + @Transactional + public void deleteById(Long id) { + bookRepository.deleteById(id); + } + + @Transactional(readOnly = true) + public Page findUpdatedSince(Instant since, int page, int pageSize) { + return bookRepository.findByUpdatedAtAfterOrderByUpdatedAtAsc( + since, PageRequest.of(page - 1, pageSize)); + } + + @Transactional(readOnly = true) + public long countUpdatedSince(Instant since) { + return bookRepository.countByUpdatedAtAfter(since); + } + + @Transactional(readOnly = true) + public Optional findLatestUpdatedAt() { + return bookRepository.findLatestUpdatedAt(); + } + + @Transactional(readOnly = true) + public List findDeletedSince(Instant since) { + return bookRepository.findDeletedBooksSince(since); + } +} diff --git a/typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/service/TypesenseService.java b/typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/service/TypesenseService.java new file mode 100644 index 0000000..ed226fa --- /dev/null +++ b/typesense-springboot-full-text-search/src/main/java/org/typesense/full_text_search/service/TypesenseService.java @@ -0,0 +1,266 @@ +package org.typesense.full_text_search.service; + +import java.time.Instant; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import java.util.stream.Collectors; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.data.domain.Page; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Service; +import org.typesense.api.Client; +import org.typesense.api.FieldTypes; +import org.typesense.model.CollectionResponse; +import org.typesense.model.CollectionSchema; +import org.typesense.model.DeleteDocumentsParameters; +import org.typesense.model.Field; +import org.typesense.model.ImportDocumentsParameters; +import org.typesense.model.IndexAction; +import org.typesense.model.SearchParameters; +import org.typesense.model.SearchResult; +import org.typesense.full_text_search.model.Book; + + +@Service +public class TypesenseService { + + private static final Logger log = LoggerFactory.getLogger(TypesenseService.class); + + private final Client client; + private final BookService bookService; + + @Value("${typesense.collection-name}") + private String collectionName; + + @Value("${typesense.sync.batch-size}") + private int batchSize; + + @Value("${typesense.sync.page-size}") + private int pageSize; + + @Value("${typesense.sync.enable-soft-delete}") + private boolean enableSoftDelete; + + private final AtomicReference lastSyncTime = new AtomicReference<>(Instant.EPOCH); + private final AtomicBoolean syncWorkerRunning = new AtomicBoolean(false); + + public TypesenseService(Client client, BookService bookService) { + this.client = client; + this.bookService = bookService; + } + + // --- Sync state accessors (thread-safe) --- + + public Instant getLastSyncTime() { + return lastSyncTime.get(); + } + + public void setLastSyncTime(Instant time) { + lastSyncTime.set(time); + } + + public boolean isSyncWorkerRunning() { + return syncWorkerRunning.get(); + } + + public void setSyncWorkerRunning(boolean running) { + syncWorkerRunning.set(running); + } + + // --- Collection management --- + + public void initializeCollection() throws Exception { + log.info("Initializing Typesense collection '{}'...", collectionName); + try { + client.collections(collectionName).retrieve(); + log.info("Collection '{}' already exists, skipping creation", collectionName); + } catch (Exception e) { + log.info("Collection '{}' not found, creating...", collectionName); + CollectionSchema schema = new CollectionSchema(); + schema.name(collectionName) + .fields(List.of( + new Field().name("title").type(FieldTypes.STRING).facet(false), + new Field().name("authors").type(FieldTypes.STRING_ARRAY).facet(true), + new Field().name("publication_year").type(FieldTypes.INT32).facet(true), + new Field().name("average_rating").type(FieldTypes.FLOAT).facet(true), + new Field().name("image_url").type(FieldTypes.STRING).facet(false), + new Field().name("ratings_count").type(FieldTypes.INT32).facet(true).sort(true) + )) + .defaultSortingField("ratings_count"); + client.collections().create(schema); + log.info("Collection '{}' created successfully", collectionName); + } + } + + public long collectionDocumentCount() { + try { + CollectionResponse response = client.collections(collectionName).retrieve(); + return response.getNumDocuments() != null ? response.getNumDocuments() : 0; + } catch (Exception e) { + return 0; + } + } + + // --- Search --- + + public SearchResult search(String query) throws Exception { + SearchParameters params = new SearchParameters() + .q(query) + .queryBy("title,authors") + .queryByWeights("2,1") + .facetBy("authors,publication_year,average_rating"); + return client.collections(collectionName).documents().search(params); + } + + // --- Incremental sync --- + + public Instant syncBooksToTypesense(Instant since) throws Exception { + log.info("Starting incremental sync since {}", since); + + long updatedCount = bookService.countUpdatedSince(since); + if (updatedCount == 0) { + log.info("No changes to sync"); + return Instant.now(); + } + + int totalPages = (int) Math.ceil((double) updatedCount / pageSize); + log.info("Found {} books to sync ({} pages)", updatedCount, totalPages); + + int totalSuccess = 0; + int totalFailure = 0; + + for (int page = 1; page <= totalPages; page++) { + Page books = bookService.findUpdatedSince(since, page, pageSize); + if (!books.hasContent()) break; + + log.info("Processing page {}/{} ({} books)", page, totalPages, books.getNumberOfElements()); + + String jsonl = booksToJsonl(books.getContent()); + ImportDocumentsParameters importParams = new ImportDocumentsParameters(); + importParams.action(IndexAction.UPSERT); + + String response = client.collections(collectionName).documents().import_(jsonl, importParams); + int[] counts = countImportResults(response); + totalSuccess += counts[0]; + totalFailure += counts[1]; + + log.info("Page {}/{}: {} succeeded, {} failed", page, totalPages, counts[0], counts[1]); + } + + Instant newSyncTime = Instant.now(); + log.info("Incremental sync completed: {} upserted, {} failed out of {} total", + totalSuccess, totalFailure, updatedCount); + return newSyncTime; + } + + // --- Soft delete sync --- + + public int syncSoftDeletesToTypesense(Instant since) throws Exception { + List deletedBooks = bookService.findDeletedSince(since); + if (deletedBooks.isEmpty()) return 0; + + String idFilter = deletedBooks.stream() + .map(Book::getTypesenseId) + .collect(Collectors.joining(",")); + String filterBy = "id:[" + idFilter + "]"; + + log.info("Deleting {} documents from Typesense", deletedBooks.size()); + + DeleteDocumentsParameters params = new DeleteDocumentsParameters(); + params.filterBy(filterBy); + client.collections(collectionName).documents().delete(params); + + log.info("Successfully deleted {} documents from Typesense", deletedBooks.size()); + return deletedBooks.size(); + } + + // --- Single document sync (for real-time CRUD operations) --- + + @Async("typesenseAsyncExecutor") + public void syncBookAsync(Book book) { + try { + client.collections(collectionName).documents().upsert(bookToDocument(book)); + setLastSyncTime(Instant.now()); + log.info("Synced book to Typesense: id={}, title={}", book.getId(), book.getTitle()); + } catch (Exception e) { + log.error("Async Typesense sync failed for book {}: {}", book.getId(), e.getMessage()); + } + } + + @Async("typesenseAsyncExecutor") + public void deleteBookAsync(Long bookId) { + try { + String documentId = "book_" + bookId; + client.collections(collectionName).documents(documentId).delete(); + setLastSyncTime(Instant.now()); + log.info("Deleted book from Typesense: id={}", bookId); + } catch (Exception e) { + log.error("Async Typesense deletion failed for book {}: {}", bookId, e.getMessage()); + } + } + + // --- Helpers --- + + private Map bookToDocument(Book book) { + Map doc = new HashMap<>(); + doc.put("id", book.getTypesenseId()); + doc.put("title", book.getTitle()); + doc.put("authors", book.getAuthors() != null ? book.getAuthors() : List.of()); + doc.put("publication_year", book.getPublicationYear() != null ? book.getPublicationYear() : 0); + doc.put("average_rating", book.getAverageRating() != null ? book.getAverageRating() : 0.0); + doc.put("image_url", book.getImageUrl() != null ? book.getImageUrl() : ""); + doc.put("ratings_count", book.getRatingsCount() != null ? book.getRatingsCount() : 0); + return doc; + } + + private String booksToJsonl(List books) { + return books.stream() + .map(this::bookToJsonLine) + .collect(Collectors.joining("\n")); + } + + private String bookToJsonLine(Book book) { + String authors = "[]"; + if (book.getAuthors() != null && !book.getAuthors().isEmpty()) { + authors = "[" + book.getAuthors().stream() + .map(a -> "\"" + escapeJson(a) + "\"") + .collect(Collectors.joining(",")) + "]"; + } + return "{" + + "\"id\":\"" + escapeJson(book.getTypesenseId()) + "\"," + + "\"title\":\"" + escapeJson(book.getTitle() != null ? book.getTitle() : "") + "\"," + + "\"authors\":" + authors + "," + + "\"publication_year\":" + (book.getPublicationYear() != null ? book.getPublicationYear() : 0) + "," + + "\"average_rating\":" + (book.getAverageRating() != null ? book.getAverageRating() : 0.0) + "," + + "\"image_url\":\"" + escapeJson(book.getImageUrl() != null ? book.getImageUrl() : "") + "\"," + + "\"ratings_count\":" + (book.getRatingsCount() != null ? book.getRatingsCount() : 0) + + "}"; + } + + private static String escapeJson(String value) { + if (value == null) return ""; + return value.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n").replace("\r", "\\r"); + } + + private int[] countImportResults(String response) { + int success = 0, failure = 0; + if (response == null || response.isBlank()) return new int[]{success, failure}; + for (String line : response.split("\n")) { + if (line.contains("\"success\":true")) { + success++; + } else { + failure++; + if (failure <= 5) { + log.warn("Import error: {}", line); + } + } + } + return new int[]{success, failure}; + } +} diff --git a/typesense-springboot-full-text-search/src/main/resources/application.properties b/typesense-springboot-full-text-search/src/main/resources/application.properties new file mode 100644 index 0000000..4ba09e0 --- /dev/null +++ b/typesense-springboot-full-text-search/src/main/resources/application.properties @@ -0,0 +1,27 @@ +spring.application.name=full-text-search +server.port=${PORT:4000} + +# Database Configuration +spring.datasource.url=jdbc:postgresql://${DB_HOST}:${DB_PORT}/${DB_NAME} +spring.datasource.username=${DB_USER} +spring.datasource.password=${DB_PASSWORD} +spring.datasource.driver-class-name=org.postgresql.Driver + +# JPA / Hibernate +spring.jpa.hibernate.ddl-auto=${HIBERNATE_DDL_AUTO:update} +spring.jpa.open-in-view=false +spring.jpa.properties.hibernate.jdbc.time_zone=UTC + +# Typesense Configuration +typesense.host=${TYPESENSE_HOST} +typesense.port=${TYPESENSE_PORT} +typesense.protocol=${TYPESENSE_PROTOCOL} +typesense.api-key=${TYPESENSE_API_KEY} +typesense.collection-name=${TYPESENSE_COLLECTION_NAME} +typesense.connection-timeout-seconds=${TYPESENSE_CONNECTION_TIMEOUT} + +# Sync Configuration +typesense.sync.interval-ms=${TYPESENSE_SYNC_INTERVAL:60000} +typesense.sync.batch-size=${TYPESENSE_SYNC_BATCH_SIZE:1000} +typesense.sync.page-size=${TYPESENSE_SYNC_PAGE_SIZE:1000} +typesense.sync.enable-soft-delete=${TYPESENSE_SYNC_ENABLE_SOFT_DELETE:true} diff --git a/typesense-springboot-full-text-search/src/test/java/org/typesense/full_text_search/FullTextSearchApplicationTests.java b/typesense-springboot-full-text-search/src/test/java/org/typesense/full_text_search/FullTextSearchApplicationTests.java new file mode 100644 index 0000000..31059e2 --- /dev/null +++ b/typesense-springboot-full-text-search/src/test/java/org/typesense/full_text_search/FullTextSearchApplicationTests.java @@ -0,0 +1,14 @@ +package org.typesense.full_text_search; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertNotNull; + +class FullTextSearchApplicationTests { + + @Test + void applicationClassExists() { + assertNotNull(FullTextSearchApplication.class); + } + +} From f00cd351458c0a38bcce36c87b21b35482c8ca82 Mon Sep 17 00:00:00 2001 From: Nikhiladiga Date: Sat, 25 Apr 2026 13:18:41 +0530 Subject: [PATCH 02/15] First revision: update sample env file with dummy db credentials --- typesense-springboot-full-text-search/.env.example | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/typesense-springboot-full-text-search/.env.example b/typesense-springboot-full-text-search/.env.example index 9463c54..0f84697 100644 --- a/typesense-springboot-full-text-search/.env.example +++ b/typesense-springboot-full-text-search/.env.example @@ -5,8 +5,8 @@ PORT=4000 DB_HOST=localhost DB_PORT=5432 DB_NAME=typesense_books -DB_USER=myuser -DB_PASSWORD=mypassword +DB_USER=xxx +DB_PASSWORD=xxx # JPA / Hibernate HIBERNATE_DDL_AUTO=update From 1f515a0b832a31b0f61f365f4d77e63da583a16c Mon Sep 17 00:00:00 2001 From: Nikhiladiga Date: Sat, 2 May 2026 12:34:44 +0530 Subject: [PATCH 03/15] [FEAT]: implement Typesense search integration with PostgreSQL and Sequelize for full-text search and background sync --- .../.env.example | 15 ++ .../README.md | 212 ++++++++++++++++++ .../package.json | 29 +++ .../src/config/database.ts | 15 ++ .../src/config/env.ts | 18 ++ .../src/models/Book.ts | 79 +++++++ .../src/routes/books.ts | 127 +++++++++++ .../src/routes/search.ts | 53 +++++ .../src/search/client.ts | 14 ++ .../src/search/collections.ts | 35 +++ .../src/search/sync.ts | 148 ++++++++++++ .../src/search/worker.ts | 31 +++ .../src/server.ts | 51 +++++ .../tsconfig.json | 14 ++ 14 files changed, 841 insertions(+) create mode 100644 typesense-node-sequelize-full-text-search/.env.example create mode 100644 typesense-node-sequelize-full-text-search/README.md create mode 100644 typesense-node-sequelize-full-text-search/package.json create mode 100644 typesense-node-sequelize-full-text-search/src/config/database.ts create mode 100644 typesense-node-sequelize-full-text-search/src/config/env.ts create mode 100644 typesense-node-sequelize-full-text-search/src/models/Book.ts create mode 100644 typesense-node-sequelize-full-text-search/src/routes/books.ts create mode 100644 typesense-node-sequelize-full-text-search/src/routes/search.ts create mode 100644 typesense-node-sequelize-full-text-search/src/search/client.ts create mode 100644 typesense-node-sequelize-full-text-search/src/search/collections.ts create mode 100644 typesense-node-sequelize-full-text-search/src/search/sync.ts create mode 100644 typesense-node-sequelize-full-text-search/src/search/worker.ts create mode 100644 typesense-node-sequelize-full-text-search/src/server.ts create mode 100644 typesense-node-sequelize-full-text-search/tsconfig.json diff --git a/typesense-node-sequelize-full-text-search/.env.example b/typesense-node-sequelize-full-text-search/.env.example new file mode 100644 index 0000000..9b6d483 --- /dev/null +++ b/typesense-node-sequelize-full-text-search/.env.example @@ -0,0 +1,15 @@ +# Server Configuration +PORT=3000 + +# Database Configuration +DB_HOST=localhost +DB_USER=postgres +DB_PASSWORD=password +DB_NAME=typesense_books +DB_PORT=5432 + +# Typesense Configuration +TYPESENSE_HOST=localhost +TYPESENSE_PORT=8108 +TYPESENSE_PROTOCOL=http +TYPESENSE_API_KEY=xyz diff --git a/typesense-node-sequelize-full-text-search/README.md b/typesense-node-sequelize-full-text-search/README.md new file mode 100644 index 0000000..447e8e8 --- /dev/null +++ b/typesense-node-sequelize-full-text-search/README.md @@ -0,0 +1,212 @@ +# Node.js Express Full-Text Search with Typesense + +A production-ready RESTful search API built with Node.js, Express, PostgreSQL (Sequelize), and Typesense. Features full-text search, CRUD operations, real-time async indexing, and background sync workers. + +## Tech Stack + +- Node.js +- Express +- PostgreSQL with Sequelize +- Typesense +- TypeScript +- Docker + +## Prerequisites + +- Node.js v18+ installed +- Docker (for Typesense and PostgreSQL) +- Basic knowledge of REST APIs and SQL + +## Quick Start + +### 1. Clone the repository + +```bash +git clone https://github.com/typesense/code-samples.git +cd typesense-node-sequelize-search-app +``` + +### 2. Install dependencies + +```bash +npm install +``` + +### 3. Start Typesense and PostgreSQL + +Run Typesense and PostgreSQL using Docker: + +```bash +# Start Typesense (replace TYPESENSE_VERSION with the latest from https://typesense.org/docs/guide/install-typesense.html) +docker run -d \ + -p 8108:8108 \ + -v typesense-data:/data \ + typesense/typesense:27.1 \ + --data-dir /data \ + --api-key=xyz \ + --enable-cors + +# Start PostgreSQL +docker run -d \ + -p 5432:5432 \ + -e POSTGRES_USER=postgres \ + -e POSTGRES_PASSWORD=password \ + -e POSTGRES_DB=typesense_books \ + -v postgres-data:/var/lib/postgresql/data \ + postgres:15 +``` + +### 4. Set up environment variables + +Create a `.env` file in the project root by copying `.env.example`: + +```bash +cp .env.example .env +``` + +### 5. Project Structure + +```text +├── src/ +│ ├── config/ +│ │ ├── database.ts # Sequelize configuration +│ │ └── env.ts # Environment variable validation +│ ├── models/ +│ │ └── Book.ts # Sequelize Book model +│ ├── routes/ +│ │ ├── books.ts # CRUD endpoints for books +│ │ └── search.ts # Search and sync endpoints +│ ├── search/ +│ │ ├── client.ts # Typesense client initialization +│ │ ├── collections.ts # Typesense collection schema +│ │ ├── sync.ts # Sync logic (incremental, full, soft delete) +│ │ └── worker.ts # Background sync worker +│ └── server.ts # Main application entry point +├── package.json +├── tsconfig.json +└── .env +``` + +### 6. Start the development server + +```bash +npm run dev +``` + +The server will automatically restart when you make changes to any TypeScript file. + +Open [http://localhost:3000](http://localhost:3000) in your browser. + +### 7. API Endpoints + +#### Search + +```bash +GET /search?q= +``` + +Example: + +```bash +curl "http://localhost:3000/search?q=harry" +``` + +#### CRUD Operations + +**Create a book:** + +```bash +POST /books +Content-Type: application/json + +{ + "title": "The Go Programming Language", + "authors": ["Alan Donovan", "Brian Kernighan"], + "publication_year": 2015, + "average_rating": 4.5, + "image_url": "https://example.com/image.jpg", + "ratings_count": 1000 +} +``` + +**Get a book:** + +```bash +GET /books/:id +``` + +**Get all books (with pagination):** + +```bash +GET /books?page=1&limit=10 +``` + +**Update a book:** + +```bash +PUT /books/:id +Content-Type: application/json + +{ + "title": "Updated Title", + "authors": ["Author Name"], + "publication_year": 2024, + "average_rating": 4.8, + "image_url": "https://example.com/updated.jpg", + "ratings_count": 1500 +} +``` + +**Delete a book (soft delete):** + +```bash +DELETE /books/:id +``` + +#### Sync Operations + +**Trigger manual sync:** + +```bash +POST /sync +``` + +**Check sync status:** + +```bash +GET /sync/status +``` + +### 8. How It Works + +#### Architecture + +```plaintext +User Request + ↓ +Express API (CRUD) + ↓ +PostgreSQL (Source of Truth) + ↓ +Async Sync → Typesense (Search Index) + ↑ +Background Worker (Every 60s) +``` + +#### Sync Strategies + +##### 1. Startup Sync (Smart) + +On every server start, the sync worker checks whether the Typesense collection already has documents. If empty, it seeds `lastSyncTime` to zero and runs a full sync. If it has data, it runs an incremental sync since `MAX(updated_at)` of PostgreSQL books table. + +##### 2. Real-time Sync (Async) + +Triggered on Create, Update, Delete operations in the background. + +##### 3. Background Periodic Sync + +Runs every 60 seconds automatically, doing incremental sync. + +##### 4. Manual Sync + +Endpoint: `POST /sync` diff --git a/typesense-node-sequelize-full-text-search/package.json b/typesense-node-sequelize-full-text-search/package.json new file mode 100644 index 0000000..73d21b2 --- /dev/null +++ b/typesense-node-sequelize-full-text-search/package.json @@ -0,0 +1,29 @@ +{ + "name": "typesense-node-sequelize-search-app", + "version": "1.0.0", + "description": "A production-ready RESTful search API built with Node.js, Express, PostgreSQL, and Typesense.", + "main": "dist/server.js", + "scripts": { + "start": "node dist/server.js", + "dev": "ts-node-dev --respawn --transpile-only src/server.ts", + "build": "tsc" + }, + "dependencies": { + "cors": "^2.8.5", + "dotenv": "^16.4.5", + "express": "^4.19.2", + "node-cron": "^3.0.3", + "pg": "^8.11.5", + "pg-hstore": "^2.3.4", + "sequelize": "^6.37.3", + "typesense": "^1.8.2" + }, + "devDependencies": { + "@types/cors": "^2.8.17", + "@types/express": "^4.17.21", + "@types/node": "^20.12.7", + "@types/node-cron": "^3.0.11", + "ts-node-dev": "^2.0.0", + "typescript": "^5.4.5" + } +} diff --git a/typesense-node-sequelize-full-text-search/src/config/database.ts b/typesense-node-sequelize-full-text-search/src/config/database.ts new file mode 100644 index 0000000..1f22f20 --- /dev/null +++ b/typesense-node-sequelize-full-text-search/src/config/database.ts @@ -0,0 +1,15 @@ +import { Sequelize } from 'sequelize'; +import { env } from './env'; + +export const sequelize = new Sequelize(env.DB_NAME, env.DB_USER, env.DB_PASSWORD, { + host: env.DB_HOST, + port: env.DB_PORT, + dialect: 'postgres', + logging: console.log, + pool: { + max: 5, + min: 0, + acquire: 30000, + idle: 10000 + } +}); diff --git a/typesense-node-sequelize-full-text-search/src/config/env.ts b/typesense-node-sequelize-full-text-search/src/config/env.ts new file mode 100644 index 0000000..ca37595 --- /dev/null +++ b/typesense-node-sequelize-full-text-search/src/config/env.ts @@ -0,0 +1,18 @@ +import dotenv from 'dotenv'; + +dotenv.config(); + +export const env = { + PORT: parseInt(process.env.PORT || '3000', 10), + + DB_HOST: process.env.DB_HOST || 'localhost', + DB_USER: process.env.DB_USER || 'postgres', + DB_PASSWORD: process.env.DB_PASSWORD || 'password', + DB_NAME: process.env.DB_NAME || 'typesense_books', + DB_PORT: parseInt(process.env.DB_PORT || '5432', 10), + + TYPESENSE_HOST: process.env.TYPESENSE_HOST || 'localhost', + TYPESENSE_PORT: parseInt(process.env.TYPESENSE_PORT || '8108', 10), + TYPESENSE_PROTOCOL: process.env.TYPESENSE_PROTOCOL || 'http', + TYPESENSE_API_KEY: process.env.TYPESENSE_API_KEY || 'xyz', +}; diff --git a/typesense-node-sequelize-full-text-search/src/models/Book.ts b/typesense-node-sequelize-full-text-search/src/models/Book.ts new file mode 100644 index 0000000..4ae8f54 --- /dev/null +++ b/typesense-node-sequelize-full-text-search/src/models/Book.ts @@ -0,0 +1,79 @@ +import { Model, DataTypes, type Optional } from 'sequelize'; +import { sequelize } from '../config/database'; + +export interface BookAttributes { + id: number; + title: string; + authors: string[]; + publication_year: number; + average_rating: number; + image_url: string; + ratings_count: number; + created_at?: Date; + updated_at?: Date; + deleted_at?: Date | null; +} + +export interface BookCreationAttributes extends Optional {} + +export class Book extends Model implements BookAttributes { + declare id: number; + declare title: string; + declare authors: string[]; + declare publication_year: number; + declare average_rating: number; + declare image_url: string; + declare ratings_count: number; + + declare readonly created_at: Date; + declare readonly updated_at: Date; + declare readonly deleted_at: Date | null; +} + +Book.init( + { + id: { + type: DataTypes.INTEGER, + autoIncrement: true, + primaryKey: true, + }, + title: { + type: DataTypes.STRING(255), + allowNull: false, + }, + authors: { + type: DataTypes.JSONB, + allowNull: false, + defaultValue: [], + }, + publication_year: { + type: DataTypes.INTEGER, + allowNull: true, + }, + average_rating: { + type: DataTypes.DECIMAL(3, 2), + allowNull: true, + get() { + const value = this.getDataValue('average_rating'); + return value === null ? null : parseFloat(value as unknown as string); + } + }, + image_url: { + type: DataTypes.STRING(255), + allowNull: true, + }, + ratings_count: { + type: DataTypes.INTEGER, + allowNull: true, + }, + }, + { + sequelize, + tableName: 'books', + timestamps: true, + paranoid: true, // Enables soft deletes (deletedAt) + createdAt: 'created_at', + updatedAt: 'updated_at', + deletedAt: 'deleted_at', + } +); diff --git a/typesense-node-sequelize-full-text-search/src/routes/books.ts b/typesense-node-sequelize-full-text-search/src/routes/books.ts new file mode 100644 index 0000000..17794c0 --- /dev/null +++ b/typesense-node-sequelize-full-text-search/src/routes/books.ts @@ -0,0 +1,127 @@ +import { Router, type Request, type Response } from 'express'; +import { Book } from '../models/Book'; +import { typesenseClient } from '../search/client'; +import { BOOKS_COLLECTION_NAME } from '../search/collections'; + +const router = Router(); + +// Helper for real-time async sync +const syncBookToTypesense = async (book: Book) => { + try { + const document = { + id: book.id.toString(), + title: book.title, + authors: Array.isArray(book.authors) ? book.authors : [book.authors], + publication_year: book.publication_year || 0, + average_rating: typeof book.average_rating === 'number' ? book.average_rating : parseFloat(book.average_rating || '0'), + image_url: book.image_url || '', + ratings_count: book.ratings_count || 0, + }; + + console.log(`Syncing book ${book.id} to Typesense:`, document.title); + await typesenseClient.collections(BOOKS_COLLECTION_NAME).documents().upsert(document); + console.log(`Successfully synced book ${book.id} to Typesense.`); + } catch (err) { + console.error(`Failed to sync book ${book.id} to Typesense:`, err); + throw err; + } +}; + +const deleteBookFromTypesense = async (id: number) => { + try { + await typesenseClient.collections(BOOKS_COLLECTION_NAME).documents(id.toString()).delete(); + } catch (err) { + console.error(`Failed to delete book ${id} from Typesense`, err); + } +}; + +// GET /books - Get all books with pagination +router.get('/', async (req: Request, res: Response) => { + const page = parseInt(req.query.page as string || '1', 10); + const limit = parseInt(req.query.limit as string || '10', 10); + const offset = (page - 1) * limit; + + try { + const { count, rows } = await Book.findAndCountAll({ + limit, + offset, + order: [['id', 'ASC']] + }); + + res.json({ + total: count, + page, + limit, + data: rows + }); + } catch (_error) { + res.status(500).json({ error: 'Failed to fetch books' }); + } +}); + +// GET /books/:id - Get a book +router.get('/:id', async (req: Request, res: Response) => { + try { + const book = await Book.findByPk(req.params.id); + if (!book) { + return res.status(404).json({ error: 'Book not found' }); + } + res.json(book); + } catch (_error) { + res.status(500).json({ error: 'Failed to fetch book' }); + } +}); + +// POST /books - Create a book +router.post('/', async (req: Request, res: Response) => { + try { + const book = await Book.create(req.body); + + // Real-time async sync (now awaited to ensure consistency in tests) + await syncBookToTypesense(book); + + res.status(201).json(book); + } catch (error) { + res.status(400).json({ error: (error as Error).message }); + } +}); + +// PUT /books/:id - Update a book +router.put('/:id', async (req: Request, res: Response) => { + try { + const book = await Book.findByPk(req.params.id); + if (!book) { + return res.status(404).json({ error: 'Book not found' }); + } + + await book.update(req.body); + + // Real-time async sync (now awaited to ensure consistency in tests) + await syncBookToTypesense(book); + + res.json(book); + } catch (error) { + res.status(400).json({ error: (error as Error).message }); + } +}); + +// DELETE /books/:id - Delete a book +router.delete('/:id', async (req: Request, res: Response) => { + try { + const book = await Book.findByPk(req.params.id); + if (!book) { + return res.status(404).json({ error: 'Book not found' }); + } + + await book.destroy(); + + // Real-time async sync + deleteBookFromTypesense(book.id); + + res.status(204).send(); + } catch (error) { + res.status(500).json({ error: (error as Error).message }); + } +}); + +export default router; diff --git a/typesense-node-sequelize-full-text-search/src/routes/search.ts b/typesense-node-sequelize-full-text-search/src/routes/search.ts new file mode 100644 index 0000000..7daa5eb --- /dev/null +++ b/typesense-node-sequelize-full-text-search/src/routes/search.ts @@ -0,0 +1,53 @@ +import { Router, type Request, type Response } from 'express'; +import { typesenseClient } from '../search/client'; +import { BOOKS_COLLECTION_NAME } from '../search/collections'; +import { runFullSync, lastSyncTime } from '../search/sync'; +import { getSyncStatus } from '../search/worker'; + +const router = Router(); + +// GET /search?q= +router.get('/search', async (req: Request, res: Response) => { + const query = req.query.q as string || ''; + + try { + const searchResults = await typesenseClient.collections(BOOKS_COLLECTION_NAME).documents().search({ + q: query, + query_by: 'title,authors', + }); + + res.json({ + query, + found: searchResults.found, + results: searchResults.hits, + facet_counts: searchResults.facet_counts || [], + }); + } catch (_error) { + res.status(500).json({ error: 'Failed to fetch books' }); + } +}); + +// POST /sync - Trigger manual sync +router.post('/sync', async (_req: Request, res: Response) => { + try { + // We run full sync here for manual trigger, but you could also run incremental + await runFullSync(); + + res.json({ + message: 'Sync completed', + syncedAt: lastSyncTime.toISOString() + }); + } catch (_error) { + res.status(500).json({ error: 'Failed to sync books' }); + } +}); + +// GET /sync/status - Check sync status +router.get('/sync/status', (_req: Request, res: Response) => { + res.json({ + lastSyncTime: lastSyncTime.toISOString(), + syncWorkerRunning: getSyncStatus().syncWorkerRunning + }); +}); + +export default router; diff --git a/typesense-node-sequelize-full-text-search/src/search/client.ts b/typesense-node-sequelize-full-text-search/src/search/client.ts new file mode 100644 index 0000000..97ca2dc --- /dev/null +++ b/typesense-node-sequelize-full-text-search/src/search/client.ts @@ -0,0 +1,14 @@ +import { Client } from 'typesense'; +import { env } from '../config/env'; + +export const typesenseClient = new Client({ + nodes: [ + { + host: env.TYPESENSE_HOST, + port: env.TYPESENSE_PORT, + protocol: env.TYPESENSE_PROTOCOL, + }, + ], + apiKey: env.TYPESENSE_API_KEY, + connectionTimeoutSeconds: 5, +}); diff --git a/typesense-node-sequelize-full-text-search/src/search/collections.ts b/typesense-node-sequelize-full-text-search/src/search/collections.ts new file mode 100644 index 0000000..28d478d --- /dev/null +++ b/typesense-node-sequelize-full-text-search/src/search/collections.ts @@ -0,0 +1,35 @@ +import type { CollectionCreateSchema } from 'typesense/lib/Typesense/Collections'; +import { typesenseClient } from './client'; + +export const BOOKS_COLLECTION_NAME = 'books'; + +export const booksCollectionSchema: CollectionCreateSchema = { + name: BOOKS_COLLECTION_NAME, + fields: [ + { name: 'id', type: 'string' }, + { name: 'title', type: 'string' }, + { name: 'authors', type: 'string[]', facet: true }, + { name: 'publication_year', type: 'int32', facet: true, optional: true }, + { name: 'average_rating', type: 'float', facet: true, optional: true }, + { name: 'image_url', type: 'string', optional: true }, + { name: 'ratings_count', type: 'int32', optional: true }, + ], +}; + +export async function initializeTypesense(): Promise { + try { + const collections = await typesenseClient.collections().retrieve(); + const collectionExists = collections.some((c) => c.name === BOOKS_COLLECTION_NAME); + + if (!collectionExists) { + console.log(`Creating collection ${BOOKS_COLLECTION_NAME}...`); + await typesenseClient.collections().create(booksCollectionSchema); + console.log(`Collection ${BOOKS_COLLECTION_NAME} created successfully.`); + } else { + console.log(`Collection ${BOOKS_COLLECTION_NAME} already exists.`); + } + } catch (error) { + console.error('Error initializing Typesense collection:', error); + throw error; + } +} diff --git a/typesense-node-sequelize-full-text-search/src/search/sync.ts b/typesense-node-sequelize-full-text-search/src/search/sync.ts new file mode 100644 index 0000000..3a809b9 --- /dev/null +++ b/typesense-node-sequelize-full-text-search/src/search/sync.ts @@ -0,0 +1,148 @@ +import { Op } from 'sequelize'; +import { Book } from '../models/Book'; +import { typesenseClient } from './client'; +import { BOOKS_COLLECTION_NAME } from './collections'; + +export let lastSyncTime: Date = new Date(0); + +const BATCH_SIZE = 1000; + +export async function runFullSync() { + console.log('Running full sync...'); + let lastId = 0; + let hasMore = true; + let totalProcessed = 0; + + while (hasMore) { + let books: Book[]; + try { + books = await Book.findAll({ + where: { id: { [Op.gt]: lastId } }, + limit: BATCH_SIZE, + order: [['id', 'ASC']], + paranoid: true, // Only fetch active records + }); + } catch (err) { + console.error('Database error during full sync fetching:', err); + break; // Abort this sync run gracefully on DB failure + } + + if (books.length === 0) { + hasMore = false; + break; + } + + lastId = books[books.length - 1].id; + + const documents = books.map((b) => ({ + id: b.id.toString(), + title: b.title, + authors: b.authors, + publication_year: b.publication_year || 0, + average_rating: b.average_rating || 0.0, + image_url: b.image_url || '', + ratings_count: b.ratings_count || 0, + })); + + try { + await typesenseClient.collections(BOOKS_COLLECTION_NAME).documents().import(documents, { action: 'upsert' }); + totalProcessed += documents.length; + console.log(`Full sync: Processed ${totalProcessed} books.`); + } catch (err) { + console.error('Error importing documents during full sync', err); + // We can choose to break or continue here; breaking is safer on Typesense errors + break; + } + } + + // Update lastSyncTime to now + lastSyncTime = new Date(); + console.log('Full sync completed.'); +} + +export async function runIncrementalSync() { + console.log(`Running incremental sync since ${lastSyncTime.toISOString()}...`); + + // 1. Find newly created or updated books + const updatedBooks = await Book.findAll({ + where: { + updated_at: { + [Op.gt]: lastSyncTime, + }, + }, + paranoid: true, // Only active + }); + + if (updatedBooks.length > 0) { + const documents = updatedBooks.map((b) => ({ + id: b.id.toString(), + title: b.title, + authors: b.authors, + publication_year: b.publication_year || 0, + average_rating: b.average_rating || 0.0, + image_url: b.image_url || '', + ratings_count: b.ratings_count || 0, + })); + + try { + await typesenseClient.collections(BOOKS_COLLECTION_NAME).documents().import(documents, { action: 'upsert' }); + console.log(`Incremental sync: Upserted ${documents.length} books.`); + } catch (err) { + console.error('Error upserting documents in incremental sync', err); + } + } + + // 2. Find soft-deleted books + const deletedBooks = await Book.findAll({ + where: { + deleted_at: { + [Op.gt]: lastSyncTime, + }, + }, + paranoid: false, // Include soft-deleted + }); + + if (deletedBooks.length > 0) { + for (const book of deletedBooks) { + try { + await typesenseClient.collections(BOOKS_COLLECTION_NAME).documents(book.id.toString()).delete(); + console.log(`Incremental sync: Deleted book ${book.id} from Typesense.`); + } catch (err) { + // Typesense might return 404 if document doesn't exist, which is fine + const error = err as { httpStatus?: number }; + if (error.httpStatus !== 404) { + console.error(`Error deleting book ${book.id} from Typesense`, err); + } + } + } + } + + lastSyncTime = new Date(); + console.log('Incremental sync completed.'); +} + +export async function determineAndRunStartupSync() { + try { + const searchStats = await typesenseClient.collections(BOOKS_COLLECTION_NAME).retrieve(); + const docCount = searchStats.num_documents; + + if (docCount === 0) { + // Empty Typesense collection, full sync + await runFullSync(); + } else { + // Typesense has data, get latest updated_at from DB + const latestBook = await Book.findOne({ + order: [['updated_at', 'DESC']], + paranoid: false, // Check across all records + }); + + if (latestBook?.updated_at) { + lastSyncTime = latestBook.updated_at; + } + + await runIncrementalSync(); + } + } catch (error) { + console.error('Error during startup sync:', error); + } +} diff --git a/typesense-node-sequelize-full-text-search/src/search/worker.ts b/typesense-node-sequelize-full-text-search/src/search/worker.ts new file mode 100644 index 0000000..775aa48 --- /dev/null +++ b/typesense-node-sequelize-full-text-search/src/search/worker.ts @@ -0,0 +1,31 @@ +import cron from 'node-cron'; +import { runIncrementalSync } from './sync'; + +let isSyncRunning = false; + +export function startBackgroundSyncWorker() { + console.log('Starting background periodic sync worker (every 60s)...'); + + // Runs every minute + cron.schedule('* * * * *', async () => { + if (isSyncRunning) { + console.log('Sync already running, skipping this iteration.'); + return; + } + + isSyncRunning = true; + try { + await runIncrementalSync(); + } catch (error) { + console.error('Error in background sync worker:', error); + } finally { + isSyncRunning = false; + } + }); +} + +export function getSyncStatus() { + return { + syncWorkerRunning: isSyncRunning, + }; +} diff --git a/typesense-node-sequelize-full-text-search/src/server.ts b/typesense-node-sequelize-full-text-search/src/server.ts new file mode 100644 index 0000000..ef8e23c --- /dev/null +++ b/typesense-node-sequelize-full-text-search/src/server.ts @@ -0,0 +1,51 @@ +import express from 'express'; +import cors from 'cors'; +import { env } from './config/env'; +import { sequelize } from './config/database'; +import { initializeTypesense } from './search/collections'; +import { determineAndRunStartupSync } from './search/sync'; +import { startBackgroundSyncWorker } from './search/worker'; + +import booksRouter from './routes/books'; +import searchRouter from './routes/search'; + +const app = express(); + +app.use(cors()); +app.use(express.json()); + +// Routes +app.use('/books', booksRouter); +app.use('/', searchRouter); + +async function startServer() { + try { + // 1. Connect to PostgreSQL + console.log('Connecting to PostgreSQL database...'); + await sequelize.authenticate(); + // In production, use migrations instead of sync() + await sequelize.sync(); + console.log('Database connected and models synced.'); + + // 2. Initialize Typesense + console.log('Initializing Typesense...'); + await initializeTypesense(); + + // 3. Run Startup Sync + console.log('Running startup sync...'); + await determineAndRunStartupSync(); + + // 4. Start Background Worker + startBackgroundSyncWorker(); + + // 5. Start Express API + app.listen(env.PORT, () => { + console.log(`Server is running on http://localhost:${env.PORT}`); + }); + } catch (error) { + console.error('Failed to start server:', error); + process.exit(1); + } +} + +startServer(); diff --git a/typesense-node-sequelize-full-text-search/tsconfig.json b/typesense-node-sequelize-full-text-search/tsconfig.json new file mode 100644 index 0000000..24cf495 --- /dev/null +++ b/typesense-node-sequelize-full-text-search/tsconfig.json @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "target": "es2022", + "module": "commonjs", + "rootDir": "./src", + "outDir": "./dist", + "esModuleInterop": true, + "forceConsistentCasingInFileNames": true, + "strict": true, + "skipLibCheck": true, + "resolveJsonModule": true + }, + "include": ["src/**/*"] +} From 15a27c476588cf871e38b9bfdb3fea7ffc60292a Mon Sep 17 00:00:00 2001 From: Nikhiladiga Date: Sun, 10 May 2026 09:55:34 +0530 Subject: [PATCH 04/15] First revision: add Node.js Sequelize app to README and include Typesense syntax guide for agents --- README.md | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 55e83e9..c779ee1 100644 --- a/README.md +++ b/README.md @@ -8,17 +8,18 @@ This is a monorepo containing multiple standalone projects. Each project lives i ```plaintext code-samples/ -├── typesense-angular-search-bar/ # Angular + Typesense search implementation -├── typesense-astro-search/ # Astro + Typesense search implementation -├── typesense-gin-full-text-search/ # Go (Gin) + Typesense backend implementation -├── typesense-next-search-bar/ # Next.js + Typesense search implementation -├── typesense-nuxt-search-bar/ # Nuxt.js + Typesense search implementation -├── typesense-qwik-js-search/ # Qwik + Typesense search implementation -├── typesense-react-native-search-bar/ # React Native + Typesense search implementation -├── typesense-solid-js-search/ # SolidJS + Typesense search implementation -├── typesense-springboot-full-text-search/ # Spring Boot + Typesense backend implementation -├── typesense-vanilla-js-search/ # Vanilla JS + Typesense search implementation -└── README.md # You are here +├── typesense-angular-search-bar/ # Angular + Typesense search implementation +├── typesense-astro-search/ # Astro + Typesense search implementation +├── typesense-gin-full-text-search/ # Go (Gin) + Typesense backend implementation +├── typesense-next-search-bar/ # Next.js + Typesense search implementation +├── typesense-nuxt-search-bar/ # Nuxt.js + Typesense search implementation +├── typesense-qwik-js-search/ # Qwik + Typesense search implementation +├── typesense-react-native-search-bar/ # React Native + Typesense search implementation +├── typesense-solid-js-search/ # SolidJS + Typesense search implementation +├── typesense-springboot-full-text-search/ # Spring Boot + Typesense backend implementation +├── typesense-node-sequelize-search-app/ # Node.js (Express) + Typesense + Sequelize backend implementation +├── typesense-vanilla-js-search/ # Vanilla JS + Typesense search implementation +└── README.md # You are here ``` ## Projects @@ -34,6 +35,7 @@ code-samples/ | [typesense-react-native-search-bar](./typesense-react-native-search-bar) | React Native | A mobile search bar with instant search capabilities | | [typesense-solid-js-search](./typesense-solid-js-search) | SolidJS | A modern search bar with instant search capabilities | | [typesense-springboot-full-text-search](./typesense-springboot-full-text-search) | Spring Boot | Backend API with full-text search using Typesense | +| [typesense-node-sequelize-search-app](./typesense-node-sequelize-search-app) | Node.js (Express) + Typesense + Sequelize | Backend API with full-text search using Typesense | | [typesense-vanilla-js-search](./typesense-vanilla-js-search) | Vanilla JS | A modern search bar with instant search capabilities | ## Getting Started From 8e31239907896b1dfc17295ae47cc80aa87af6ba Mon Sep 17 00:00:00 2001 From: Nikhiladiga Date: Sat, 2 May 2026 13:56:49 +0530 Subject: [PATCH 05/15] [FEAT]: implement Typesense-integrated Node.js and Prisma full-text search API with async background syncing --- .../.env.example | 15 ++ .../.gitignore | 5 + .../README.md | 231 ++++++++++++++++++ .../package.json | 30 +++ .../prisma.config.ts | 14 ++ .../20260502073537_init_books/migration.sql | 15 ++ .../prisma/migrations/migration_lock.toml | 3 + .../prisma/schema.prisma | 22 ++ .../src/config/database.ts | 13 + .../src/config/env.ts | 18 ++ .../src/routes/books.ts | 155 ++++++++++++ .../src/routes/search.ts | 53 ++++ .../src/search/client.ts | 14 ++ .../src/search/collections.ts | 35 +++ .../src/search/sync.ts | 184 ++++++++++++++ .../src/search/worker.ts | 31 +++ .../src/server.ts | 49 ++++ .../tsconfig.json | 14 ++ 18 files changed, 901 insertions(+) create mode 100644 typesense-node-prisma-full-text-search/.env.example create mode 100644 typesense-node-prisma-full-text-search/.gitignore create mode 100644 typesense-node-prisma-full-text-search/README.md create mode 100644 typesense-node-prisma-full-text-search/package.json create mode 100644 typesense-node-prisma-full-text-search/prisma.config.ts create mode 100644 typesense-node-prisma-full-text-search/prisma/migrations/20260502073537_init_books/migration.sql create mode 100644 typesense-node-prisma-full-text-search/prisma/migrations/migration_lock.toml create mode 100644 typesense-node-prisma-full-text-search/prisma/schema.prisma create mode 100644 typesense-node-prisma-full-text-search/src/config/database.ts create mode 100644 typesense-node-prisma-full-text-search/src/config/env.ts create mode 100644 typesense-node-prisma-full-text-search/src/routes/books.ts create mode 100644 typesense-node-prisma-full-text-search/src/routes/search.ts create mode 100644 typesense-node-prisma-full-text-search/src/search/client.ts create mode 100644 typesense-node-prisma-full-text-search/src/search/collections.ts create mode 100644 typesense-node-prisma-full-text-search/src/search/sync.ts create mode 100644 typesense-node-prisma-full-text-search/src/search/worker.ts create mode 100644 typesense-node-prisma-full-text-search/src/server.ts create mode 100644 typesense-node-prisma-full-text-search/tsconfig.json diff --git a/typesense-node-prisma-full-text-search/.env.example b/typesense-node-prisma-full-text-search/.env.example new file mode 100644 index 0000000..9b6d483 --- /dev/null +++ b/typesense-node-prisma-full-text-search/.env.example @@ -0,0 +1,15 @@ +# Server Configuration +PORT=3000 + +# Database Configuration +DB_HOST=localhost +DB_USER=postgres +DB_PASSWORD=password +DB_NAME=typesense_books +DB_PORT=5432 + +# Typesense Configuration +TYPESENSE_HOST=localhost +TYPESENSE_PORT=8108 +TYPESENSE_PROTOCOL=http +TYPESENSE_API_KEY=xyz diff --git a/typesense-node-prisma-full-text-search/.gitignore b/typesense-node-prisma-full-text-search/.gitignore new file mode 100644 index 0000000..126419d --- /dev/null +++ b/typesense-node-prisma-full-text-search/.gitignore @@ -0,0 +1,5 @@ +node_modules +# Keep environment variables out of version control +.env + +/src/generated/prisma diff --git a/typesense-node-prisma-full-text-search/README.md b/typesense-node-prisma-full-text-search/README.md new file mode 100644 index 0000000..652bfc0 --- /dev/null +++ b/typesense-node-prisma-full-text-search/README.md @@ -0,0 +1,231 @@ +# Node.js Express Full-Text Search with Typesense + +A production-ready RESTful search API built with Node.js, Express, PostgreSQL (Prisma), and Typesense. Features full-text search, CRUD operations, real-time async indexing, and background sync workers. + +## Tech Stack + +- Node.js +- Express +- PostgreSQL with Prisma ORM +- Typesense +- TypeScript +- Docker + +## Prerequisites + +- Node.js v18+ installed +- Docker (for Typesense and PostgreSQL) +- Basic knowledge of REST APIs and SQL + +## Quick Start + +### 1. Clone the repository + +```bash +git clone https://github.com/typesense/code-samples.git +cd typesense-node-prisma-full-text-search +``` + +### 2. Install dependencies + +```bash +npm install +``` + +### 3. Start Typesense and PostgreSQL + +Run Typesense and PostgreSQL using Docker: + +```bash +# Start Typesense (replace TYPESENSE_VERSION with the latest from https://typesense.org/docs/guide/install-typesense.html) +docker run -d \ + -p 8108:8108 \ + -v typesense-data:/data \ + typesense/typesense:27.1 \ + --data-dir /data \ + --api-key=xyz \ + --enable-cors + +# Start PostgreSQL +docker run -d \ + -p 5432:5432 \ + -e POSTGRES_USER=postgres \ + -e POSTGRES_PASSWORD=password \ + -e POSTGRES_DB=typesense_books \ + -v postgres-data:/var/lib/postgresql/data \ + postgres:15 +``` + +### 4. Set up environment variables + +Create a `.env` file in the project root by copying `.env.example`: + +```bash +cp .env.example .env +``` + +### 5. Project Structure + +```text +├── prisma/ +│ └── schema.prisma # Prisma schema and model definitions +├── src/ +│ ├── config/ +│ │ ├── database.ts # Prisma Client instantiation +│ │ └── env.ts # Environment variable validation +│ ├── routes/ +│ │ ├── books.ts # CRUD endpoints for books +│ │ └── search.ts # Search and sync endpoints +│ ├── search/ +│ │ ├── client.ts # Typesense client initialization +│ │ ├── collections.ts # Typesense collection schema +│ │ ├── sync.ts # Sync logic (incremental, full, soft delete) +│ │ └── worker.ts # Background sync worker +│ └── server.ts # Main application entry point +├── package.json +├── tsconfig.json +└── .env +``` + +### 6. Database Migrations + +**Development Environment:** +When building out your schema or making changes during development, use the `db push` command. It pushes your schema state directly to the database without generating history: +```bash +npx prisma db push +``` + +**Production Environment:** +For production, you should use Prisma Migrate to generate and apply consistent database migrations. +Generate a migration (run this in dev when ready): +```bash +npx prisma migrate dev --name init_books +``` +Apply migrations safely in production (e.g., during your CI/CD pipeline): +```bash +npx prisma migrate deploy +``` + +### 7. Start the development server + +```bash +npm run dev +``` + +The server will automatically restart when you make changes to any TypeScript file. + +Open [http://localhost:3000](http://localhost:3000) in your browser. + +### 8. API Endpoints + +#### Search + +```bash +GET /search?q= +``` + +Example: + +```bash +curl "http://localhost:3000/search?q=harry" +``` + +#### CRUD Operations + +**Create a book:** + +```bash +POST /books +Content-Type: application/json + +{ + "title": "The Go Programming Language", + "authors": ["Alan Donovan", "Brian Kernighan"], + "publication_year": 2015, + "average_rating": 4.5, + "image_url": "https://example.com/image.jpg", + "ratings_count": 1000 +} +``` + +**Get a book:** + +```bash +GET /books/:id +``` + +**Get all books (with pagination):** + +```bash +GET /books?page=1&limit=10 +``` + +**Update a book:** + +```bash +PUT /books/:id +Content-Type: application/json + +{ + "title": "Updated Title", + "authors": ["Author Name"], + "publication_year": 2024, + "average_rating": 4.8, + "image_url": "https://example.com/updated.jpg", + "ratings_count": 1500 +} +``` + +**Delete a book (soft delete):** + +```bash +DELETE /books/:id +``` + +#### Sync Operations + +**Trigger manual sync:** + +```bash +POST /sync +``` + +**Check sync status:** + +```bash +GET /sync/status +``` + +### 9. How It Works + +#### Architecture + +```plaintext +User Request + ↓ +Express API (CRUD) + ↓ +PostgreSQL (Source of Truth) + ↓ +Async Sync → Typesense (Search Index) + ↑ +Background Worker (Every 60s) +``` + +#### Sync Strategies + +##### 1. Startup Sync (Smart) + +On every server start, the sync worker checks whether the Typesense collection already has documents. If empty, it seeds `lastSyncTime` to zero and runs a full sync. If it has data, it runs an incremental sync since `MAX(updated_at)` of PostgreSQL books table. + +##### 2. Real-time Sync (Async) + +Triggered on Create, Update, Delete operations in the background. + +##### 3. Background Periodic Sync + +Runs every 60 seconds automatically, doing incremental sync. + +##### 4. Manual Sync + +Endpoint: `POST /sync` diff --git a/typesense-node-prisma-full-text-search/package.json b/typesense-node-prisma-full-text-search/package.json new file mode 100644 index 0000000..d7d7c65 --- /dev/null +++ b/typesense-node-prisma-full-text-search/package.json @@ -0,0 +1,30 @@ +{ + "name": "typesense-node-prisma-search-app", + "version": "1.0.0", + "description": "A production-ready RESTful search API built with Node.js, Express, PostgreSQL, and Typesense.", + "main": "dist/server.js", + "scripts": { + "start": "node dist/server.js", + "dev": "ts-node-dev --respawn --transpile-only src/server.ts", + "build": "tsc" + }, + "dependencies": { + "@prisma/adapter-pg": "^7.8.0", + "@prisma/client": "^7.8.0", + "cors": "^2.8.5", + "dotenv": "^16.4.5", + "express": "^4.19.2", + "node-cron": "^3.0.3", + "pg": "^8.20.0", + "typesense": "^1.8.2" + }, + "devDependencies": { + "@types/cors": "^2.8.17", + "@types/express": "^4.17.21", + "@types/node": "^20.12.7", + "@types/node-cron": "^3.0.11", + "prisma": "^7.8.0", + "ts-node-dev": "^2.0.0", + "typescript": "^5.4.5" + } +} diff --git a/typesense-node-prisma-full-text-search/prisma.config.ts b/typesense-node-prisma-full-text-search/prisma.config.ts new file mode 100644 index 0000000..831a20f --- /dev/null +++ b/typesense-node-prisma-full-text-search/prisma.config.ts @@ -0,0 +1,14 @@ +// This file was generated by Prisma, and assumes you have installed the following: +// npm install --save-dev prisma dotenv +import "dotenv/config"; +import { defineConfig } from "prisma/config"; + +export default defineConfig({ + schema: "prisma/schema.prisma", + migrations: { + path: "prisma/migrations", + }, + datasource: { + url: process.env["DATABASE_URL"], + }, +}); diff --git a/typesense-node-prisma-full-text-search/prisma/migrations/20260502073537_init_books/migration.sql b/typesense-node-prisma-full-text-search/prisma/migrations/20260502073537_init_books/migration.sql new file mode 100644 index 0000000..235560e --- /dev/null +++ b/typesense-node-prisma-full-text-search/prisma/migrations/20260502073537_init_books/migration.sql @@ -0,0 +1,15 @@ +-- CreateTable +CREATE TABLE "books" ( + "id" SERIAL NOT NULL, + "title" VARCHAR(255) NOT NULL, + "authors" JSONB NOT NULL DEFAULT '[]', + "publication_year" INTEGER, + "average_rating" DECIMAL(3,2), + "image_url" VARCHAR(255), + "ratings_count" INTEGER, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + "deleted_at" TIMESTAMP(3), + + CONSTRAINT "books_pkey" PRIMARY KEY ("id") +); diff --git a/typesense-node-prisma-full-text-search/prisma/migrations/migration_lock.toml b/typesense-node-prisma-full-text-search/prisma/migrations/migration_lock.toml new file mode 100644 index 0000000..044d57c --- /dev/null +++ b/typesense-node-prisma-full-text-search/prisma/migrations/migration_lock.toml @@ -0,0 +1,3 @@ +# Please do not edit this file manually +# It should be added in your version-control system (e.g., Git) +provider = "postgresql" diff --git a/typesense-node-prisma-full-text-search/prisma/schema.prisma b/typesense-node-prisma-full-text-search/prisma/schema.prisma new file mode 100644 index 0000000..9b5e64d --- /dev/null +++ b/typesense-node-prisma-full-text-search/prisma/schema.prisma @@ -0,0 +1,22 @@ +generator client { + provider = "prisma-client-js" +} + +datasource db { + provider = "postgresql" +} + +model Book { + id Int @id @default(autoincrement()) + title String @db.VarChar(255) + authors Json @default("[]") + publication_year Int? + average_rating Decimal? @db.Decimal(3, 2) + image_url String? @db.VarChar(255) + ratings_count Int? + created_at DateTime @default(now()) + updated_at DateTime @updatedAt + deleted_at DateTime? + + @@map("books") +} diff --git a/typesense-node-prisma-full-text-search/src/config/database.ts b/typesense-node-prisma-full-text-search/src/config/database.ts new file mode 100644 index 0000000..3bc2212 --- /dev/null +++ b/typesense-node-prisma-full-text-search/src/config/database.ts @@ -0,0 +1,13 @@ +import { PrismaClient } from '@prisma/client'; +import { PrismaPg } from '@prisma/adapter-pg'; +import { Pool } from 'pg'; + +const connectionString = process.env.DATABASE_URL; + +const pool = new Pool({ connectionString }); +const adapter = new PrismaPg(pool); + +export const prisma = new PrismaClient({ + adapter, + log: ['query', 'info', 'warn', 'error'], +}); diff --git a/typesense-node-prisma-full-text-search/src/config/env.ts b/typesense-node-prisma-full-text-search/src/config/env.ts new file mode 100644 index 0000000..ca37595 --- /dev/null +++ b/typesense-node-prisma-full-text-search/src/config/env.ts @@ -0,0 +1,18 @@ +import dotenv from 'dotenv'; + +dotenv.config(); + +export const env = { + PORT: parseInt(process.env.PORT || '3000', 10), + + DB_HOST: process.env.DB_HOST || 'localhost', + DB_USER: process.env.DB_USER || 'postgres', + DB_PASSWORD: process.env.DB_PASSWORD || 'password', + DB_NAME: process.env.DB_NAME || 'typesense_books', + DB_PORT: parseInt(process.env.DB_PORT || '5432', 10), + + TYPESENSE_HOST: process.env.TYPESENSE_HOST || 'localhost', + TYPESENSE_PORT: parseInt(process.env.TYPESENSE_PORT || '8108', 10), + TYPESENSE_PROTOCOL: process.env.TYPESENSE_PROTOCOL || 'http', + TYPESENSE_API_KEY: process.env.TYPESENSE_API_KEY || 'xyz', +}; diff --git a/typesense-node-prisma-full-text-search/src/routes/books.ts b/typesense-node-prisma-full-text-search/src/routes/books.ts new file mode 100644 index 0000000..5c9702c --- /dev/null +++ b/typesense-node-prisma-full-text-search/src/routes/books.ts @@ -0,0 +1,155 @@ +import { Router, type Request, type Response } from 'express'; +import { prisma } from '../config/database'; +import type { Book } from '@prisma/client'; +import { typesenseClient } from '../search/client'; +import { BOOKS_COLLECTION_NAME } from '../search/collections'; + +const router = Router(); + +// Helper for real-time async sync +const syncBookToTypesense = async (book: Book) => { + try { + // Prisma returns JSON as Prisma.JsonValue, we cast to array for typesense + const authorsArray = Array.isArray(book.authors) ? book.authors : [book.authors]; + + const document = { + id: book.id.toString(), + title: book.title, + authors: authorsArray as string[], + publication_year: book.publication_year || 0, + average_rating: book.average_rating ? Number(book.average_rating) : 0, + image_url: book.image_url || '', + ratings_count: book.ratings_count || 0, + }; + + console.log(`Syncing book ${book.id} to Typesense:`, document.title); + await typesenseClient.collections(BOOKS_COLLECTION_NAME).documents().upsert(document); + console.log(`Successfully synced book ${book.id} to Typesense.`); + } catch (err) { + console.error(`Failed to sync book ${book.id} to Typesense:`, err); + throw err; + } +}; + +const deleteBookFromTypesense = async (id: number) => { + try { + await typesenseClient.collections(BOOKS_COLLECTION_NAME).documents(id.toString()).delete(); + } catch (err) { + console.error(`Failed to delete book ${id} from Typesense`, err); + } +}; + +// GET /books - Get all books with pagination +router.get('/', async (req: Request, res: Response) => { + const page = parseInt(req.query.page as string || '1', 10); + const limit = parseInt(req.query.limit as string || '10', 10); + const offset = (page - 1) * limit; + + try { + const [count, rows] = await Promise.all([ + prisma.book.count({ where: { deleted_at: null } }), + prisma.book.findMany({ + where: { deleted_at: null }, + skip: offset, + take: limit, + orderBy: { id: 'asc' } + }) + ]); + + res.json({ + total: count, + page, + limit, + data: rows + }); + } catch (error) { + console.error(error); + res.status(500).json({ error: 'Failed to fetch books' }); + } +}); + +// GET /books/:id - Get a book +router.get('/:id', async (req: Request, res: Response) => { + try { + const book = await prisma.book.findUnique({ + where: { + id: parseInt(req.params.id), + deleted_at: null + } + }); + + if (!book) { + return res.status(404).json({ error: 'Book not found' }); + } + res.json(book); + } catch (error) { + res.status(500).json({ error: 'Failed to fetch book' }); + } +}); + +// POST /books - Create a book +router.post('/', async (req: Request, res: Response) => { + try { + const book = await prisma.book.create({ + data: req.body + }); + + // Real-time async sync + await syncBookToTypesense(book); + + res.status(201).json(book); + } catch (error) { + res.status(400).json({ error: (error as Error).message }); + } +}); + +// PUT /books/:id - Update a book +router.put('/:id', async (req: Request, res: Response) => { + try { + const bookId = parseInt(req.params.id); + const existingBook = await prisma.book.findUnique({ where: { id: bookId, deleted_at: null } }); + + if (!existingBook) { + return res.status(404).json({ error: 'Book not found' }); + } + + const updatedBook = await prisma.book.update({ + where: { id: bookId }, + data: req.body + }); + + // Real-time async sync + await syncBookToTypesense(updatedBook); + + res.json(updatedBook); + } catch (error) { + res.status(400).json({ error: (error as Error).message }); + } +}); + +// DELETE /books/:id - Delete a book +router.delete('/:id', async (req: Request, res: Response) => { + try { + const bookId = parseInt(req.params.id); + const existingBook = await prisma.book.findUnique({ where: { id: bookId, deleted_at: null } }); + + if (!existingBook) { + return res.status(404).json({ error: 'Book not found' }); + } + + // Soft delete + await prisma.book.update({ + where: { id: bookId }, + data: { deleted_at: new Date() } + }); + + // Real-time async sync + deleteBookFromTypesense(bookId); + + res.status(204).send(); + } catch (error) { + res.status(500).json({ error: (error as Error).message }); + } +}); + +export default router; diff --git a/typesense-node-prisma-full-text-search/src/routes/search.ts b/typesense-node-prisma-full-text-search/src/routes/search.ts new file mode 100644 index 0000000..7daa5eb --- /dev/null +++ b/typesense-node-prisma-full-text-search/src/routes/search.ts @@ -0,0 +1,53 @@ +import { Router, type Request, type Response } from 'express'; +import { typesenseClient } from '../search/client'; +import { BOOKS_COLLECTION_NAME } from '../search/collections'; +import { runFullSync, lastSyncTime } from '../search/sync'; +import { getSyncStatus } from '../search/worker'; + +const router = Router(); + +// GET /search?q= +router.get('/search', async (req: Request, res: Response) => { + const query = req.query.q as string || ''; + + try { + const searchResults = await typesenseClient.collections(BOOKS_COLLECTION_NAME).documents().search({ + q: query, + query_by: 'title,authors', + }); + + res.json({ + query, + found: searchResults.found, + results: searchResults.hits, + facet_counts: searchResults.facet_counts || [], + }); + } catch (_error) { + res.status(500).json({ error: 'Failed to fetch books' }); + } +}); + +// POST /sync - Trigger manual sync +router.post('/sync', async (_req: Request, res: Response) => { + try { + // We run full sync here for manual trigger, but you could also run incremental + await runFullSync(); + + res.json({ + message: 'Sync completed', + syncedAt: lastSyncTime.toISOString() + }); + } catch (_error) { + res.status(500).json({ error: 'Failed to sync books' }); + } +}); + +// GET /sync/status - Check sync status +router.get('/sync/status', (_req: Request, res: Response) => { + res.json({ + lastSyncTime: lastSyncTime.toISOString(), + syncWorkerRunning: getSyncStatus().syncWorkerRunning + }); +}); + +export default router; diff --git a/typesense-node-prisma-full-text-search/src/search/client.ts b/typesense-node-prisma-full-text-search/src/search/client.ts new file mode 100644 index 0000000..97ca2dc --- /dev/null +++ b/typesense-node-prisma-full-text-search/src/search/client.ts @@ -0,0 +1,14 @@ +import { Client } from 'typesense'; +import { env } from '../config/env'; + +export const typesenseClient = new Client({ + nodes: [ + { + host: env.TYPESENSE_HOST, + port: env.TYPESENSE_PORT, + protocol: env.TYPESENSE_PROTOCOL, + }, + ], + apiKey: env.TYPESENSE_API_KEY, + connectionTimeoutSeconds: 5, +}); diff --git a/typesense-node-prisma-full-text-search/src/search/collections.ts b/typesense-node-prisma-full-text-search/src/search/collections.ts new file mode 100644 index 0000000..28d478d --- /dev/null +++ b/typesense-node-prisma-full-text-search/src/search/collections.ts @@ -0,0 +1,35 @@ +import type { CollectionCreateSchema } from 'typesense/lib/Typesense/Collections'; +import { typesenseClient } from './client'; + +export const BOOKS_COLLECTION_NAME = 'books'; + +export const booksCollectionSchema: CollectionCreateSchema = { + name: BOOKS_COLLECTION_NAME, + fields: [ + { name: 'id', type: 'string' }, + { name: 'title', type: 'string' }, + { name: 'authors', type: 'string[]', facet: true }, + { name: 'publication_year', type: 'int32', facet: true, optional: true }, + { name: 'average_rating', type: 'float', facet: true, optional: true }, + { name: 'image_url', type: 'string', optional: true }, + { name: 'ratings_count', type: 'int32', optional: true }, + ], +}; + +export async function initializeTypesense(): Promise { + try { + const collections = await typesenseClient.collections().retrieve(); + const collectionExists = collections.some((c) => c.name === BOOKS_COLLECTION_NAME); + + if (!collectionExists) { + console.log(`Creating collection ${BOOKS_COLLECTION_NAME}...`); + await typesenseClient.collections().create(booksCollectionSchema); + console.log(`Collection ${BOOKS_COLLECTION_NAME} created successfully.`); + } else { + console.log(`Collection ${BOOKS_COLLECTION_NAME} already exists.`); + } + } catch (error) { + console.error('Error initializing Typesense collection:', error); + throw error; + } +} diff --git a/typesense-node-prisma-full-text-search/src/search/sync.ts b/typesense-node-prisma-full-text-search/src/search/sync.ts new file mode 100644 index 0000000..d6173de --- /dev/null +++ b/typesense-node-prisma-full-text-search/src/search/sync.ts @@ -0,0 +1,184 @@ +import { prisma } from '../config/database'; +import { typesenseClient } from './client'; +import { BOOKS_COLLECTION_NAME } from './collections'; +import type { Book } from '@prisma/client'; + +export let lastSyncTime: Date = new Date(0); + +const BATCH_SIZE = 1000; + +const mapBookToTypesense = (b: Book) => ({ + id: b.id.toString(), + title: b.title, + authors: (Array.isArray(b.authors) ? b.authors : [b.authors]) as string[], + publication_year: b.publication_year || 0, + average_rating: b.average_rating ? Number(b.average_rating) : 0, + image_url: b.image_url || '', + ratings_count: b.ratings_count || 0, +}); + +export async function runFullSync() { + console.log('Running full sync...'); + let lastId = 0; + let hasMore = true; + let totalProcessed = 0; + + while (hasMore) { + let books: Book[]; + try { + books = await prisma.book.findMany({ + where: { + id: { gt: lastId }, + deleted_at: null + }, + take: BATCH_SIZE, + orderBy: { id: 'asc' } + }); + } catch (err) { + console.error('Database error during full sync fetching:', err); + break; // Abort this sync run gracefully on DB failure + } + + if (books.length === 0) { + hasMore = false; + break; + } + + lastId = books[books.length - 1].id; + + const documents = books.map(mapBookToTypesense); + + try { + await typesenseClient.collections(BOOKS_COLLECTION_NAME).documents().import(documents, { action: 'upsert' }); + totalProcessed += documents.length; + console.log(`Full sync: Processed ${totalProcessed} books.`); + } catch (err) { + console.error('Error importing documents during full sync', err); + break; + } + } + + // Update lastSyncTime to now + lastSyncTime = new Date(); + console.log('Full sync completed.'); +} + +export async function runIncrementalSync() { + console.log(`Running incremental sync since ${lastSyncTime.toISOString()}...`); + + // 1. Process newly created or updated books in batches + let lastUpsertId = 0; + let hasMoreUpserts = true; + let totalUpserted = 0; + + while (hasMoreUpserts) { + let updatedBooks: Book[]; + try { + updatedBooks = await prisma.book.findMany({ + where: { + updated_at: { gt: lastSyncTime }, + deleted_at: null, + id: { gt: lastUpsertId } + }, + take: BATCH_SIZE, + orderBy: { id: 'asc' } + }); + } catch (err) { + console.error('Database error during incremental sync upsert fetching:', err); + break; + } + + if (updatedBooks.length === 0) { + hasMoreUpserts = false; + break; + } + + lastUpsertId = updatedBooks[updatedBooks.length - 1].id; + const documents = updatedBooks.map(mapBookToTypesense); + + try { + await typesenseClient.collections(BOOKS_COLLECTION_NAME).documents().import(documents, { action: 'upsert' }); + totalUpserted += documents.length; + } catch (err) { + console.error('Error upserting documents in incremental sync', err); + break; + } + } + + if (totalUpserted > 0) { + console.log(`Incremental sync: Upserted ${totalUpserted} books.`); + } + + // 2. Process soft-deleted books in batches + let lastDeleteId = 0; + let hasMoreDeletes = true; + let totalDeleted = 0; + + while (hasMoreDeletes) { + let deletedBooks: Book[]; + try { + deletedBooks = await prisma.book.findMany({ + where: { + deleted_at: { gt: lastSyncTime }, + id: { gt: lastDeleteId } + }, + take: BATCH_SIZE, + orderBy: { id: 'asc' } + }); + } catch (err) { + console.error('Database error during incremental sync delete fetching:', err); + break; + } + + if (deletedBooks.length === 0) { + hasMoreDeletes = false; + break; + } + + lastDeleteId = deletedBooks[deletedBooks.length - 1].id; + const ids = deletedBooks.map(b => b.id.toString()); + + try { + // Bulk delete in Typesense using filter_by + await typesenseClient.collections(BOOKS_COLLECTION_NAME).documents().delete({ + filter_by: `id:=[${ids.join(',')}]` + }); + totalDeleted += deletedBooks.length; + } catch (err) { + console.error('Error deleting documents in incremental sync', err); + break; + } + } + + if (totalDeleted > 0) { + console.log(`Incremental sync: Deleted ${totalDeleted} books from Typesense.`); + } + + lastSyncTime = new Date(); + console.log('Incremental sync completed.'); +} + +export async function determineAndRunStartupSync() { + try { + const searchStats = await typesenseClient.collections(BOOKS_COLLECTION_NAME).retrieve(); + const docCount = searchStats.num_documents; + + if (docCount === 0) { + // Empty Typesense collection, full sync + await runFullSync(); + } else { + // Typesense has data, get latest updated_at from DB + const latestBook = await prisma.book.findFirst({ + orderBy: { updated_at: 'desc' } + }); + + if (latestBook?.updated_at) { + lastSyncTime = latestBook.updated_at; + } + + await runIncrementalSync(); + } + } catch (error) { + console.error('Error during startup sync:', error); + } +} diff --git a/typesense-node-prisma-full-text-search/src/search/worker.ts b/typesense-node-prisma-full-text-search/src/search/worker.ts new file mode 100644 index 0000000..775aa48 --- /dev/null +++ b/typesense-node-prisma-full-text-search/src/search/worker.ts @@ -0,0 +1,31 @@ +import cron from 'node-cron'; +import { runIncrementalSync } from './sync'; + +let isSyncRunning = false; + +export function startBackgroundSyncWorker() { + console.log('Starting background periodic sync worker (every 60s)...'); + + // Runs every minute + cron.schedule('* * * * *', async () => { + if (isSyncRunning) { + console.log('Sync already running, skipping this iteration.'); + return; + } + + isSyncRunning = true; + try { + await runIncrementalSync(); + } catch (error) { + console.error('Error in background sync worker:', error); + } finally { + isSyncRunning = false; + } + }); +} + +export function getSyncStatus() { + return { + syncWorkerRunning: isSyncRunning, + }; +} diff --git a/typesense-node-prisma-full-text-search/src/server.ts b/typesense-node-prisma-full-text-search/src/server.ts new file mode 100644 index 0000000..51d78cb --- /dev/null +++ b/typesense-node-prisma-full-text-search/src/server.ts @@ -0,0 +1,49 @@ +import express from 'express'; +import cors from 'cors'; +import { env } from './config/env'; +import { prisma } from './config/database'; +import { initializeTypesense } from './search/collections'; +import { determineAndRunStartupSync } from './search/sync'; +import { startBackgroundSyncWorker } from './search/worker'; + +import booksRouter from './routes/books'; +import searchRouter from './routes/search'; + +const app = express(); + +app.use(cors()); +app.use(express.json()); + +// Routes +app.use('/books', booksRouter); +app.use('/', searchRouter); + +async function startServer() { + try { + // 1. Connect to PostgreSQL + console.log('Connecting to PostgreSQL database...'); + await prisma.$connect(); + console.log('Database connected.'); + + // 2. Initialize Typesense + console.log('Initializing Typesense...'); + await initializeTypesense(); + + // 3. Run Startup Sync + console.log('Running startup sync...'); + await determineAndRunStartupSync(); + + // 4. Start Background Worker + startBackgroundSyncWorker(); + + // 5. Start Express API + app.listen(env.PORT, () => { + console.log(`Server is running on http://localhost:${env.PORT}`); + }); + } catch (error) { + console.error('Failed to start server:', error); + process.exit(1); + } +} + +startServer(); diff --git a/typesense-node-prisma-full-text-search/tsconfig.json b/typesense-node-prisma-full-text-search/tsconfig.json new file mode 100644 index 0000000..24cf495 --- /dev/null +++ b/typesense-node-prisma-full-text-search/tsconfig.json @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "target": "es2022", + "module": "commonjs", + "rootDir": "./src", + "outDir": "./dist", + "esModuleInterop": true, + "forceConsistentCasingInFileNames": true, + "strict": true, + "skipLibCheck": true, + "resolveJsonModule": true + }, + "include": ["src/**/*"] +} From afb89e209e45a8dd1aa3700e087ee279caf43c81 Mon Sep 17 00:00:00 2001 From: Nikhiladiga Date: Sun, 10 May 2026 09:58:18 +0530 Subject: [PATCH 06/15] First revision: add Typesense Prisma search sample and agent syntax guide --- README.md | 28 +++++++++++++++------------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index c779ee1..56e081d 100644 --- a/README.md +++ b/README.md @@ -8,18 +8,19 @@ This is a monorepo containing multiple standalone projects. Each project lives i ```plaintext code-samples/ -├── typesense-angular-search-bar/ # Angular + Typesense search implementation -├── typesense-astro-search/ # Astro + Typesense search implementation -├── typesense-gin-full-text-search/ # Go (Gin) + Typesense backend implementation -├── typesense-next-search-bar/ # Next.js + Typesense search implementation -├── typesense-nuxt-search-bar/ # Nuxt.js + Typesense search implementation -├── typesense-qwik-js-search/ # Qwik + Typesense search implementation -├── typesense-react-native-search-bar/ # React Native + Typesense search implementation -├── typesense-solid-js-search/ # SolidJS + Typesense search implementation -├── typesense-springboot-full-text-search/ # Spring Boot + Typesense backend implementation -├── typesense-node-sequelize-search-app/ # Node.js (Express) + Typesense + Sequelize backend implementation -├── typesense-vanilla-js-search/ # Vanilla JS + Typesense search implementation -└── README.md # You are here +├── typesense-angular-search-bar/ # Angular + Typesense search implementation +├── typesense-astro-search/ # Astro + Typesense search implementation +├── typesense-gin-full-text-search/ # Go (Gin) + Typesense backend implementation +├── typesense-next-search-bar/ # Next.js + Typesense search implementation +├── typesense-nuxt-search-bar/ # Nuxt.js + Typesense search implementation +├── typesense-qwik-js-search/ # Qwik + Typesense search implementation +├── typesense-react-native-search-bar/ # React Native + Typesense search implementation +├── typesense-solid-js-search/ # SolidJS + Typesense search implementation +├── typesense-springboot-full-text-search/ # Spring Boot + Typesense backend implementation +├── typesense-node-prisma-full-text-search/ # Node.js (Express) + Typesense + Prisma backend implementation +├── typesense-node-sequelize-full-text-search/ # Node.js (Express) + Typesense + Sequelize backend implementation +├── typesense-vanilla-js-search/ # Vanilla JS + Typesense search implementation +└── README.md # You are here ``` ## Projects @@ -35,7 +36,8 @@ code-samples/ | [typesense-react-native-search-bar](./typesense-react-native-search-bar) | React Native | A mobile search bar with instant search capabilities | | [typesense-solid-js-search](./typesense-solid-js-search) | SolidJS | A modern search bar with instant search capabilities | | [typesense-springboot-full-text-search](./typesense-springboot-full-text-search) | Spring Boot | Backend API with full-text search using Typesense | -| [typesense-node-sequelize-search-app](./typesense-node-sequelize-search-app) | Node.js (Express) + Typesense + Sequelize | Backend API with full-text search using Typesense | +| [typesense-node-prisma-full-text-search](./typesense-node-prisma-full-text-search) | Node.js (Express) + Typesense + Prisma | Backend API with full-text search using Typesense | +| [typesense-node-sequelize-full-text-search](./typesense-node-sequelize-full-text-search) | Node.js (Express) + Typesense + Sequelize | Backend API with full-text search using Typesense | | [typesense-vanilla-js-search](./typesense-vanilla-js-search) | Vanilla JS | A modern search bar with instant search capabilities | ## Getting Started From 754746b6a392a179d452a381d1d8edc7742296c7 Mon Sep 17 00:00:00 2001 From: Nikhiladiga Date: Sat, 2 May 2026 22:28:20 +0530 Subject: [PATCH 07/15] [FEAT]: initialize Typesense and PostgreSQL project with Drizzle ORM and background synchronization --- .../README.md | 54 +++++ .../drizzle.config.ts | 11 + .../drizzle/0000_aromatic_spiral.sql | 12 ++ .../drizzle/meta/0000_snapshot.json | 95 +++++++++ .../drizzle/meta/_journal.json | 13 ++ .../package.json | 34 ++++ .../src/config/database.ts | 12 ++ .../src/config/env.ts | 27 +++ .../src/db/schema.ts | 18 ++ .../src/routes/books.ts | 137 +++++++++++++ .../src/routes/search.ts | 44 ++++ .../src/search/client.ts | 16 ++ .../src/search/collections.ts | 33 +++ .../src/search/sync.ts | 188 ++++++++++++++++++ .../src/search/worker.ts | 24 +++ .../src/server.ts | 41 ++++ .../tsconfig.json | 14 ++ 17 files changed, 773 insertions(+) create mode 100644 typesense-node-drizzle-full-text-search/README.md create mode 100644 typesense-node-drizzle-full-text-search/drizzle.config.ts create mode 100644 typesense-node-drizzle-full-text-search/drizzle/0000_aromatic_spiral.sql create mode 100644 typesense-node-drizzle-full-text-search/drizzle/meta/0000_snapshot.json create mode 100644 typesense-node-drizzle-full-text-search/drizzle/meta/_journal.json create mode 100644 typesense-node-drizzle-full-text-search/package.json create mode 100644 typesense-node-drizzle-full-text-search/src/config/database.ts create mode 100644 typesense-node-drizzle-full-text-search/src/config/env.ts create mode 100644 typesense-node-drizzle-full-text-search/src/db/schema.ts create mode 100644 typesense-node-drizzle-full-text-search/src/routes/books.ts create mode 100644 typesense-node-drizzle-full-text-search/src/routes/search.ts create mode 100644 typesense-node-drizzle-full-text-search/src/search/client.ts create mode 100644 typesense-node-drizzle-full-text-search/src/search/collections.ts create mode 100644 typesense-node-drizzle-full-text-search/src/search/sync.ts create mode 100644 typesense-node-drizzle-full-text-search/src/search/worker.ts create mode 100644 typesense-node-drizzle-full-text-search/src/server.ts create mode 100644 typesense-node-drizzle-full-text-search/tsconfig.json diff --git a/typesense-node-drizzle-full-text-search/README.md b/typesense-node-drizzle-full-text-search/README.md new file mode 100644 index 0000000..e0d9edb --- /dev/null +++ b/typesense-node-drizzle-full-text-search/README.md @@ -0,0 +1,54 @@ +# Typesense Node.js Drizzle ORM Full-Text Search App + +A production-ready RESTful search API built with Node.js, Express, Drizzle ORM, PostgreSQL, and Typesense. + +This application maintains PostgreSQL as the primary source of truth while keeping Typesense synchronously and asynchronously updated to handle fast, typo-tolerant full-text searches. + +## Features +- **Drizzle ORM Integration**: High performance, strongly-typed PostgreSQL queries. +- **Batched Incremental Sync**: Handles millions of rows without memory bloat using cursor-based pagination. +- **Soft Delete Support**: Properly handles `deleted_at` fields and purges ghosts from Typesense. +- **Cron Jobs**: Background worker keeps the database and Typesense index synchronized automatically. + +## Prerequisites +- Node.js v18+ +- Docker + +## Setup & Running + +1. **Start Typesense and PostgreSQL:** +```bash +docker run -d -p 8108:8108 \ + -v "$(pwd)"/typesense-data:/data \ + typesense/typesense:27.1 \ + --data-dir /data \ + --api-key=xyz \ + --enable-cors + +docker run -d \ + --name local_postgres \ + -e POSTGRES_USER=admin \ + -e POSTGRES_PASSWORD=admin123 \ + -e POSTGRES_DB=testdb \ + -p 5432:5432 \ + postgres:16 +``` + +2. **Install dependencies:** +```bash +npm install +``` + +3. **Generate and Run Migrations:** +Generate Drizzle migrations from `src/db/schema.ts` and push them to the database. +```bash +npx drizzle-kit generate +npx drizzle-kit push +``` + +4. **Start the application:** +```bash +npm run dev +``` + +The app will connect to PostgreSQL, initialize Typesense schemas, perform a startup sync (if needed), start the cron worker, and bind to `http://localhost:3002`. diff --git a/typesense-node-drizzle-full-text-search/drizzle.config.ts b/typesense-node-drizzle-full-text-search/drizzle.config.ts new file mode 100644 index 0000000..789f7a2 --- /dev/null +++ b/typesense-node-drizzle-full-text-search/drizzle.config.ts @@ -0,0 +1,11 @@ +import { defineConfig } from 'drizzle-kit'; +import 'dotenv/config'; + +export default defineConfig({ + schema: './src/db/schema.ts', + out: './drizzle', + dialect: 'postgresql', + dbCredentials: { + url: process.env.DATABASE_URL!, + }, +}); diff --git a/typesense-node-drizzle-full-text-search/drizzle/0000_aromatic_spiral.sql b/typesense-node-drizzle-full-text-search/drizzle/0000_aromatic_spiral.sql new file mode 100644 index 0000000..a35661c --- /dev/null +++ b/typesense-node-drizzle-full-text-search/drizzle/0000_aromatic_spiral.sql @@ -0,0 +1,12 @@ +CREATE TABLE "books" ( + "id" serial PRIMARY KEY NOT NULL, + "title" varchar(255) NOT NULL, + "authors" json DEFAULT '[]' NOT NULL, + "publication_year" integer, + "average_rating" numeric(3, 2), + "image_url" varchar(255), + "ratings_count" integer, + "created_at" timestamp DEFAULT now() NOT NULL, + "updated_at" timestamp DEFAULT CURRENT_TIMESTAMP NOT NULL, + "deleted_at" timestamp +); diff --git a/typesense-node-drizzle-full-text-search/drizzle/meta/0000_snapshot.json b/typesense-node-drizzle-full-text-search/drizzle/meta/0000_snapshot.json new file mode 100644 index 0000000..aa834f0 --- /dev/null +++ b/typesense-node-drizzle-full-text-search/drizzle/meta/0000_snapshot.json @@ -0,0 +1,95 @@ +{ + "id": "527348cf-95fc-4d6b-bb93-7beac078119f", + "prevId": "00000000-0000-0000-0000-000000000000", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.books": { + "name": "books", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "title": { + "name": "title", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true + }, + "authors": { + "name": "authors", + "type": "json", + "primaryKey": false, + "notNull": true, + "default": "'[]'" + }, + "publication_year": { + "name": "publication_year", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "average_rating": { + "name": "average_rating", + "type": "numeric(3, 2)", + "primaryKey": false, + "notNull": false + }, + "image_url": { + "name": "image_url", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false + }, + "ratings_count": { + "name": "ratings_count", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "CURRENT_TIMESTAMP" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": {}, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/typesense-node-drizzle-full-text-search/drizzle/meta/_journal.json b/typesense-node-drizzle-full-text-search/drizzle/meta/_journal.json new file mode 100644 index 0000000..8ba891d --- /dev/null +++ b/typesense-node-drizzle-full-text-search/drizzle/meta/_journal.json @@ -0,0 +1,13 @@ +{ + "version": "7", + "dialect": "postgresql", + "entries": [ + { + "idx": 0, + "version": "7", + "when": 1777712202767, + "tag": "0000_aromatic_spiral", + "breakpoints": true + } + ] +} \ No newline at end of file diff --git a/typesense-node-drizzle-full-text-search/package.json b/typesense-node-drizzle-full-text-search/package.json new file mode 100644 index 0000000..caeb1ec --- /dev/null +++ b/typesense-node-drizzle-full-text-search/package.json @@ -0,0 +1,34 @@ +{ + "name": "typesense-node-drizzle-full-text-search", + "version": "1.0.0", + "main": "index.js", + "scripts": { + "dev": "ts-node-dev --respawn --transpile-only src/server.ts", + "db:generate": "drizzle-kit generate", + "db:push": "drizzle-kit push", + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [], + "author": "", + "license": "ISC", + "description": "", + "dependencies": { + "cors": "^2.8.6", + "dotenv": "^17.4.2", + "drizzle-orm": "^0.45.2", + "express": "^5.2.1", + "node-cron": "^4.2.1", + "pg": "^8.20.0", + "typesense": "^3.0.6" + }, + "devDependencies": { + "@types/cors": "^2.8.19", + "@types/express": "^5.0.6", + "@types/node": "^25.6.0", + "@types/node-cron": "^3.0.11", + "@types/pg": "^8.20.0", + "drizzle-kit": "^0.31.10", + "ts-node-dev": "^2.0.0", + "typescript": "^6.0.3" + } +} diff --git a/typesense-node-drizzle-full-text-search/src/config/database.ts b/typesense-node-drizzle-full-text-search/src/config/database.ts new file mode 100644 index 0000000..55c64ff --- /dev/null +++ b/typesense-node-drizzle-full-text-search/src/config/database.ts @@ -0,0 +1,12 @@ +import { drizzle } from 'drizzle-orm/node-postgres'; +import { Pool } from 'pg'; +import { env } from './env'; +import * as schema from '../db/schema'; + +// Create a pg pool +const pool = new Pool({ + connectionString: env.DATABASE_URL, +}); + +// Create the Drizzle instance +export const db = drizzle(pool, { schema }); diff --git a/typesense-node-drizzle-full-text-search/src/config/env.ts b/typesense-node-drizzle-full-text-search/src/config/env.ts new file mode 100644 index 0000000..8d7fc44 --- /dev/null +++ b/typesense-node-drizzle-full-text-search/src/config/env.ts @@ -0,0 +1,27 @@ +import * as dotenv from 'dotenv'; +dotenv.config(); + +const requiredEnvs = [ + 'DATABASE_URL', + 'TYPESENSE_HOST', + 'TYPESENSE_PORT', + 'TYPESENSE_PROTOCOL', + 'TYPESENSE_API_KEY', + 'TYPESENSE_COLLECTION', +] as const; + +for (const env of requiredEnvs) { + if (!process.env[env]) { + throw new Error(`Missing required environment variable: ${env}`); + } +} + +export const env = { + PORT: process.env.PORT || 3000, + DATABASE_URL: process.env.DATABASE_URL!, + TYPESENSE_HOST: process.env.TYPESENSE_HOST!, + TYPESENSE_PORT: parseInt(process.env.TYPESENSE_PORT!, 10), + TYPESENSE_PROTOCOL: process.env.TYPESENSE_PROTOCOL!, + TYPESENSE_API_KEY: process.env.TYPESENSE_API_KEY!, + TYPESENSE_COLLECTION: process.env.TYPESENSE_COLLECTION!, +}; diff --git a/typesense-node-drizzle-full-text-search/src/db/schema.ts b/typesense-node-drizzle-full-text-search/src/db/schema.ts new file mode 100644 index 0000000..4ed7b77 --- /dev/null +++ b/typesense-node-drizzle-full-text-search/src/db/schema.ts @@ -0,0 +1,18 @@ +import { pgTable, serial, varchar, json, integer, decimal, timestamp } from 'drizzle-orm/pg-core'; +import { sql } from 'drizzle-orm'; + +export const books = pgTable('books', { + id: serial('id').primaryKey(), + title: varchar('title', { length: 255 }).notNull(), + authors: json('authors').default('[]').notNull(), + publicationYear: integer('publication_year'), + averageRating: decimal('average_rating', { precision: 3, scale: 2 }), + imageUrl: varchar('image_url', { length: 255 }), + ratingsCount: integer('ratings_count'), + createdAt: timestamp('created_at').defaultNow().notNull(), + updatedAt: timestamp('updated_at').default(sql`CURRENT_TIMESTAMP`).$onUpdate(() => sql`CURRENT_TIMESTAMP`).notNull(), + deletedAt: timestamp('deleted_at'), +}); + +export type Book = typeof books.$inferSelect; +export type NewBook = typeof books.$inferInsert; diff --git a/typesense-node-drizzle-full-text-search/src/routes/books.ts b/typesense-node-drizzle-full-text-search/src/routes/books.ts new file mode 100644 index 0000000..60885d6 --- /dev/null +++ b/typesense-node-drizzle-full-text-search/src/routes/books.ts @@ -0,0 +1,137 @@ +import { Router, type Request, type Response } from 'express'; +import { db } from '../config/database'; +import { books, type Book } from '../db/schema'; +import { eq, isNull, count } from 'drizzle-orm'; +import { typesenseClient } from '../search/client'; +import { BOOKS_COLLECTION_NAME } from '../search/collections'; + +const router = Router(); + +const syncBookToTypesense = async (book: Book) => { + try { + const authorsArray = Array.isArray(book.authors) ? book.authors : [book.authors]; + + const document = { + id: book.id.toString(), + title: book.title, + authors: authorsArray as string[], + publication_year: book.publicationYear || 0, + average_rating: book.averageRating ? Number(book.averageRating) : 0, + image_url: book.imageUrl || '', + ratings_count: book.ratingsCount || 0, + }; + + await typesenseClient.collections(BOOKS_COLLECTION_NAME).documents().upsert(document); + } catch (err) { + console.error(`Failed to sync book ${book.id} to Typesense:`, err); + throw err; + } +}; + +const deleteBookFromTypesense = async (id: number) => { + try { + await typesenseClient.collections(BOOKS_COLLECTION_NAME).documents(id.toString()).delete(); + } catch (err) { + console.error(`Failed to delete book ${id} from Typesense`, err); + } +}; + +router.get('/', async (req: Request, res: Response) => { + const page = parseInt(req.query.page as string || '1', 10); + const limit = parseInt(req.query.limit as string || '10', 10); + const offset = (page - 1) * limit; + + try { + const totalCountRes = await db.select({ value: count() }).from(books).where(isNull(books.deletedAt)); + const totalCount = totalCountRes[0].value; + + const rows = await db.select() + .from(books) + .where(isNull(books.deletedAt)) + .limit(limit) + .offset(offset) + .orderBy(books.id); + + res.json({ + total: totalCount, + page, + limit, + data: rows + }); + } catch (error) { + console.error(error); + res.status(500).json({ error: 'Failed to fetch books' }); + } +}); + +router.get('/:id', async (req: Request, res: Response) => { + try { + const bookId = parseInt(req.params.id as string); + const result = await db.select().from(books).where(eq(books.id, bookId)); + const book = result.find(b => b.deletedAt === null); + + if (!book) { + return res.status(404).json({ error: 'Book not found' }); + } + res.json(book); + } catch (error) { + res.status(500).json({ error: 'Failed to fetch book' }); + } +}); + +router.post('/', async (req: Request, res: Response) => { + try { + const result = await db.insert(books).values(req.body).returning(); + const book = result[0]; + + await syncBookToTypesense(book); + + res.status(201).json(book); + } catch (error) { + res.status(400).json({ error: (error as Error).message }); + } +}); + +router.put('/:id', async (req: Request, res: Response) => { + try { + const bookId = parseInt(req.params.id as string); + const existing = await db.select().from(books).where(eq(books.id, bookId)); + + if (existing.length === 0 || existing[0].deletedAt !== null) { + return res.status(404).json({ error: 'Book not found' }); + } + + const updated = await db.update(books) + .set({ ...req.body, updatedAt: new Date() }) + .where(eq(books.id, bookId)) + .returning(); + + const updatedBook = updated[0]; + await syncBookToTypesense(updatedBook); + + res.json(updatedBook); + } catch (error) { + res.status(400).json({ error: (error as Error).message }); + } +}); + +router.delete('/:id', async (req: Request, res: Response) => { + try { + const bookId = parseInt(req.params.id as string); + const existing = await db.select().from(books).where(eq(books.id, bookId)); + + if (existing.length === 0 || existing[0].deletedAt !== null) { + return res.status(404).json({ error: 'Book not found' }); + } + + await db.update(books).set({ deletedAt: new Date(), updatedAt: new Date() }).where(eq(books.id, bookId)); + + await deleteBookFromTypesense(bookId); + + res.status(204).send(); + } catch (error) { + res.status(500).json({ error: (error as Error).message }); + } +}); + +export default router; diff --git a/typesense-node-drizzle-full-text-search/src/routes/search.ts b/typesense-node-drizzle-full-text-search/src/routes/search.ts new file mode 100644 index 0000000..eb08614 --- /dev/null +++ b/typesense-node-drizzle-full-text-search/src/routes/search.ts @@ -0,0 +1,44 @@ +import { Router, type Request, type Response } from 'express'; +import { typesenseClient } from '../search/client'; +import { BOOKS_COLLECTION_NAME } from '../search/collections'; +import { runFullSync } from '../search/sync'; + +const router = Router(); + +// Perform search +router.get('/search', async (req: Request, res: Response) => { + const { q, query_by, ...otherParams } = req.query; + + if (!q || !query_by) { + return res.status(400).json({ error: 'Missing required query parameters: q and query_by' }); + } + + try { + const searchResults = await typesenseClient + .collections(BOOKS_COLLECTION_NAME) + .documents() + .search({ + q: q as string, + query_by: query_by as string, + ...otherParams, + }); + + res.json(searchResults); + } catch (error) { + console.error('Search error:', error); + res.status(500).json({ error: 'Search failed' }); + } +}); + +// Manual Sync endpoint +router.post('/sync', async (req: Request, res: Response) => { + try { + await runFullSync(); + res.json({ message: 'Sync completed successfully' }); + } catch (error) { + console.error('Sync failed:', error); + res.status(500).json({ error: 'Sync failed' }); + } +}); + +export default router; diff --git a/typesense-node-drizzle-full-text-search/src/search/client.ts b/typesense-node-drizzle-full-text-search/src/search/client.ts new file mode 100644 index 0000000..b8c403d --- /dev/null +++ b/typesense-node-drizzle-full-text-search/src/search/client.ts @@ -0,0 +1,16 @@ +import { Client } from 'typesense'; +import { env } from '../config/env'; + +export const typesenseClient = new Client({ + nodes: [ + { + host: env.TYPESENSE_HOST, + port: env.TYPESENSE_PORT, + protocol: env.TYPESENSE_PROTOCOL, + }, + ], + apiKey: env.TYPESENSE_API_KEY, + connectionTimeoutSeconds: 5, + retryIntervalSeconds: 1, + numRetries: 3, +}); diff --git a/typesense-node-drizzle-full-text-search/src/search/collections.ts b/typesense-node-drizzle-full-text-search/src/search/collections.ts new file mode 100644 index 0000000..e3a4489 --- /dev/null +++ b/typesense-node-drizzle-full-text-search/src/search/collections.ts @@ -0,0 +1,33 @@ +import { typesenseClient } from './client'; +import { env } from '../config/env'; +import type { CollectionCreateSchema } from 'typesense/lib/Typesense/Collections'; + +export const BOOKS_COLLECTION_NAME = env.TYPESENSE_COLLECTION; + +export async function initializeTypesense() { + const schema: CollectionCreateSchema = { + name: BOOKS_COLLECTION_NAME, + fields: [ + { name: 'title', type: 'string', facet: false }, + { name: 'authors', type: 'string[]', facet: true }, + { name: 'publication_year', type: 'int32', facet: true }, + { name: 'average_rating', type: 'float', facet: true }, + { name: 'image_url', type: 'string', facet: false }, + { name: 'ratings_count', type: 'int32', facet: true }, + ], + default_sorting_field: 'ratings_count', + }; + + try { + await typesenseClient.collections(BOOKS_COLLECTION_NAME).retrieve(); + console.log(`Collection '${BOOKS_COLLECTION_NAME}' already exists.`); + } catch (error: any) { + if (error.httpStatus === 404) { + console.log(`Collection '${BOOKS_COLLECTION_NAME}' not found. Creating...`); + await typesenseClient.collections().create(schema); + console.log(`Collection '${BOOKS_COLLECTION_NAME}' created successfully.`); + } else { + throw error; + } + } +} diff --git a/typesense-node-drizzle-full-text-search/src/search/sync.ts b/typesense-node-drizzle-full-text-search/src/search/sync.ts new file mode 100644 index 0000000..908de12 --- /dev/null +++ b/typesense-node-drizzle-full-text-search/src/search/sync.ts @@ -0,0 +1,188 @@ +import { db } from '../config/database'; +import { books, type Book } from '../db/schema'; +import { typesenseClient } from './client'; +import { BOOKS_COLLECTION_NAME } from './collections'; +import { eq, gt, isNull, and, isNotNull, desc } from 'drizzle-orm'; + +export let lastSyncTime: Date = new Date(0); + +const BATCH_SIZE = 1000; + +const mapBookToTypesense = (b: Book) => ({ + id: b.id.toString(), + title: b.title, + authors: (Array.isArray(b.authors) ? b.authors : [b.authors]) as string[], + publication_year: b.publicationYear || 0, + average_rating: b.averageRating ? Number(b.averageRating) : 0, + image_url: b.imageUrl || '', + ratings_count: b.ratingsCount || 0, +}); + +export async function runFullSync() { + console.log('Running full sync...'); + let lastId = 0; + let hasMore = true; + let totalProcessed = 0; + + while (hasMore) { + let fetchedBooks: Book[]; + try { + fetchedBooks = await db.select() + .from(books) + .where( + and( + gt(books.id, lastId), + isNull(books.deletedAt) + ) + ) + .limit(BATCH_SIZE) + .orderBy(books.id); + } catch (err) { + console.error('Database error during full sync fetching:', err); + break; + } + + if (fetchedBooks.length === 0) { + hasMore = false; + break; + } + + lastId = fetchedBooks[fetchedBooks.length - 1].id; + const documents = fetchedBooks.map(mapBookToTypesense); + + try { + await typesenseClient.collections(BOOKS_COLLECTION_NAME).documents().import(documents, { action: 'upsert' }); + totalProcessed += documents.length; + console.log(`Full sync: Processed ${totalProcessed} books.`); + } catch (err) { + console.error('Error importing documents during full sync', err); + break; + } + } + + lastSyncTime = new Date(); + console.log('Full sync completed.'); +} + +export async function runIncrementalSync() { + console.log(`Running incremental sync since ${lastSyncTime.toISOString()}...`); + + // 1. Process newly created or updated books in batches + let lastUpsertId = 0; + let hasMoreUpserts = true; + let totalUpserted = 0; + + while (hasMoreUpserts) { + let updatedBooks: Book[]; + try { + updatedBooks = await db.select() + .from(books) + .where( + and( + gt(books.updatedAt, lastSyncTime), + isNull(books.deletedAt), + gt(books.id, lastUpsertId) + ) + ) + .limit(BATCH_SIZE) + .orderBy(books.id); + } catch (err) { + console.error('Database error during incremental sync upsert fetching:', err); + break; + } + + if (updatedBooks.length === 0) { + hasMoreUpserts = false; + break; + } + + lastUpsertId = updatedBooks[updatedBooks.length - 1].id; + const documents = updatedBooks.map(mapBookToTypesense); + + try { + await typesenseClient.collections(BOOKS_COLLECTION_NAME).documents().import(documents, { action: 'upsert' }); + totalUpserted += documents.length; + } catch (err) { + console.error('Error upserting documents in incremental sync', err); + break; + } + } + + if (totalUpserted > 0) { + console.log(`Incremental sync: Upserted ${totalUpserted} books.`); + } + + // 2. Process soft-deleted books in batches + let lastDeleteId = 0; + let hasMoreDeletes = true; + let totalDeleted = 0; + + while (hasMoreDeletes) { + let deletedBooks: Book[]; + try { + deletedBooks = await db.select() + .from(books) + .where( + and( + gt(books.updatedAt, lastSyncTime), + isNotNull(books.deletedAt), + gt(books.id, lastDeleteId) + ) + ) + .limit(BATCH_SIZE) + .orderBy(books.id); + } catch (err) { + console.error('Database error during incremental sync delete fetching:', err); + break; + } + + if (deletedBooks.length === 0) { + hasMoreDeletes = false; + break; + } + + lastDeleteId = deletedBooks[deletedBooks.length - 1].id; + const ids = deletedBooks.map(b => b.id.toString()); + + try { + await typesenseClient.collections(BOOKS_COLLECTION_NAME).documents().delete({ + filter_by: `id:=[${ids.join(',')}]` + }); + totalDeleted += deletedBooks.length; + } catch (err) { + console.error('Error deleting documents in incremental sync', err); + break; + } + } + + if (totalDeleted > 0) { + console.log(`Incremental sync: Deleted ${totalDeleted} books from Typesense.`); + } + + lastSyncTime = new Date(); + console.log('Incremental sync completed.'); +} + +export async function determineAndRunStartupSync() { + try { + const searchStats = await typesenseClient.collections(BOOKS_COLLECTION_NAME).retrieve(); + const docCount = searchStats.num_documents; + + if (docCount === 0) { + await runFullSync(); + } else { + const latestBook = await db.select() + .from(books) + .orderBy(desc(books.updatedAt)) + .limit(1); + + if (latestBook.length > 0 && latestBook[0].updatedAt) { + lastSyncTime = latestBook[0].updatedAt; + } + + await runIncrementalSync(); + } + } catch (error) { + console.error('Error during startup sync:', error); + } +} diff --git a/typesense-node-drizzle-full-text-search/src/search/worker.ts b/typesense-node-drizzle-full-text-search/src/search/worker.ts new file mode 100644 index 0000000..dd35a01 --- /dev/null +++ b/typesense-node-drizzle-full-text-search/src/search/worker.ts @@ -0,0 +1,24 @@ +import cron from 'node-cron'; +import { runIncrementalSync } from './sync'; + +let isSyncRunning = false; + +export function startBackgroundSyncWorker() { + console.log('Starting background sync worker (every 60 seconds)...'); + + cron.schedule('*/60 * * * * *', async () => { + if (isSyncRunning) { + console.log('Sync already running, skipping this interval.'); + return; + } + + isSyncRunning = true; + try { + await runIncrementalSync(); + } catch (err) { + console.error('Error during background incremental sync:', err); + } finally { + isSyncRunning = false; + } + }); +} diff --git a/typesense-node-drizzle-full-text-search/src/server.ts b/typesense-node-drizzle-full-text-search/src/server.ts new file mode 100644 index 0000000..6e94f16 --- /dev/null +++ b/typesense-node-drizzle-full-text-search/src/server.ts @@ -0,0 +1,41 @@ +import express from 'express'; +import cors from 'cors'; +import { env } from './config/env'; +import { initializeTypesense } from './search/collections'; +import { determineAndRunStartupSync } from './search/sync'; +import { startBackgroundSyncWorker } from './search/worker'; + +import booksRouter from './routes/books'; +import searchRouter from './routes/search'; + +const app = express(); + +app.use(cors()); +app.use(express.json()); + +// Routes +app.use('/books', booksRouter); +app.use('/', searchRouter); + +async function startServer() { + try { + console.log('PostgreSQL database config loaded via Drizzle.'); + + console.log('Initializing Typesense...'); + await initializeTypesense(); + + console.log('Running startup sync...'); + await determineAndRunStartupSync(); + + startBackgroundSyncWorker(); + + app.listen(env.PORT, () => { + console.log(`Server is running on http://localhost:${env.PORT}`); + }); + } catch (error) { + console.error('Failed to start server:', error); + process.exit(1); + } +} + +startServer(); diff --git a/typesense-node-drizzle-full-text-search/tsconfig.json b/typesense-node-drizzle-full-text-search/tsconfig.json new file mode 100644 index 0000000..5dbd728 --- /dev/null +++ b/typesense-node-drizzle-full-text-search/tsconfig.json @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "Node16", + "moduleResolution": "Node16", + "esModuleInterop": true, + "strict": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "outDir": "./dist", + "rootDir": "./src" + }, + "include": ["src/**/*"] +} From 022bbbc7d0bddad6ca801ca285d57897e9e51086 Mon Sep 17 00:00:00 2001 From: Nikhiladiga Date: Sun, 10 May 2026 10:00:33 +0530 Subject: [PATCH 08/15] First revision: add Drizzle implementation guide to README and include Typesense syntax rules for agents --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 56e081d..f6c0632 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,7 @@ code-samples/ ├── typesense-springboot-full-text-search/ # Spring Boot + Typesense backend implementation ├── typesense-node-prisma-full-text-search/ # Node.js (Express) + Typesense + Prisma backend implementation ├── typesense-node-sequelize-full-text-search/ # Node.js (Express) + Typesense + Sequelize backend implementation +├── typesense-node-drizzle-full-text-search/ # Node.js (Express) + Typesense + Drizzle backend implementation ├── typesense-vanilla-js-search/ # Vanilla JS + Typesense search implementation └── README.md # You are here ``` @@ -38,6 +39,7 @@ code-samples/ | [typesense-springboot-full-text-search](./typesense-springboot-full-text-search) | Spring Boot | Backend API with full-text search using Typesense | | [typesense-node-prisma-full-text-search](./typesense-node-prisma-full-text-search) | Node.js (Express) + Typesense + Prisma | Backend API with full-text search using Typesense | | [typesense-node-sequelize-full-text-search](./typesense-node-sequelize-full-text-search) | Node.js (Express) + Typesense + Sequelize | Backend API with full-text search using Typesense | +| [typesense-node-drizzle-search-app](./typesense-node-drizzle-search-app) | Node.js (Express) + Typesense + Drizzle | Backend API with full-text search using Typesense | | [typesense-vanilla-js-search](./typesense-vanilla-js-search) | Vanilla JS | A modern search bar with instant search capabilities | ## Getting Started From 64de03208647394454375a58b3dffcdc16111147 Mon Sep 17 00:00:00 2001 From: Nikhiladiga Date: Fri, 15 May 2026 11:43:56 +0530 Subject: [PATCH 09/15] [FEAT]: Create sample Kotlin Android project demonstrating Typesense integration --- typesense-kotlin/.gitignore | 15 ++ typesense-kotlin/app/.gitignore | 1 + typesense-kotlin/app/build.gradle.kts | 54 ++++ typesense-kotlin/app/proguard-rules.pro | 21 ++ .../samplekotlin/ExampleInstrumentedTest.kt | 24 ++ .../app/src/main/AndroidManifest.xml | 26 ++ .../repository/TypesenseBookRepository.kt | 32 +++ .../samplekotlin/domain/model/Book.kt | 10 + .../domain/repository/BookRepository.kt | 7 + .../domain/usecase/SearchBooksUseCase.kt | 18 ++ .../samplekotlin/presentation/BookAdapter.kt | 42 +++ .../presentation/BookViewModel.kt | 40 +++ .../samplekotlin/presentation/MainActivity.kt | 105 ++++++++ .../app/src/main/res/drawable/badge_bg.xml | 6 + .../src/main/res/drawable/ic_kotlin_logo.xml | 39 +++ .../res/drawable/ic_launcher_background.xml | 170 ++++++++++++ .../res/drawable/ic_launcher_foreground.xml | 30 +++ .../app/src/main/res/drawable/search_bg.xml | 5 + .../app/src/main/res/layout/activity_main.xml | 97 +++++++ .../app/src/main/res/layout/item_book.xml | 71 +++++ .../res/mipmap-anydpi-v26/ic_launcher.xml | 6 + .../mipmap-anydpi-v26/ic_launcher_round.xml | 6 + .../src/main/res/mipmap-hdpi/ic_launcher.webp | Bin 0 -> 1404 bytes .../res/mipmap-hdpi/ic_launcher_round.webp | Bin 0 -> 2898 bytes .../src/main/res/mipmap-mdpi/ic_launcher.webp | Bin 0 -> 982 bytes .../res/mipmap-mdpi/ic_launcher_round.webp | Bin 0 -> 1772 bytes .../main/res/mipmap-xhdpi/ic_launcher.webp | Bin 0 -> 1900 bytes .../res/mipmap-xhdpi/ic_launcher_round.webp | Bin 0 -> 3918 bytes .../main/res/mipmap-xxhdpi/ic_launcher.webp | Bin 0 -> 2884 bytes .../res/mipmap-xxhdpi/ic_launcher_round.webp | Bin 0 -> 5914 bytes .../main/res/mipmap-xxxhdpi/ic_launcher.webp | Bin 0 -> 3844 bytes .../res/mipmap-xxxhdpi/ic_launcher_round.webp | Bin 0 -> 7778 bytes .../app/src/main/res/values-night/themes.xml | 17 ++ .../app/src/main/res/values/colors.xml | 14 + .../app/src/main/res/values/strings.xml | 3 + .../app/src/main/res/values/themes.xml | 17 ++ .../app/src/main/res/xml/backup_rules.xml | 13 + .../main/res/xml/data_extraction_rules.xml | 19 ++ .../typesense/samplekotlin/ExampleUnitTest.kt | 17 ++ typesense-kotlin/build.gradle.kts | 5 + typesense-kotlin/gradle.properties | 23 ++ typesense-kotlin/gradle/libs.versions.toml | 30 +++ .../gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 45457 bytes .../gradle/wrapper/gradle-wrapper.properties | 9 + typesense-kotlin/gradlew | 251 ++++++++++++++++++ typesense-kotlin/gradlew.bat | 94 +++++++ typesense-kotlin/settings.gradle.kts | 24 ++ 47 files changed, 1361 insertions(+) create mode 100644 typesense-kotlin/.gitignore create mode 100644 typesense-kotlin/app/.gitignore create mode 100644 typesense-kotlin/app/build.gradle.kts create mode 100644 typesense-kotlin/app/proguard-rules.pro create mode 100644 typesense-kotlin/app/src/androidTest/java/org/typesense/samplekotlin/ExampleInstrumentedTest.kt create mode 100644 typesense-kotlin/app/src/main/AndroidManifest.xml create mode 100644 typesense-kotlin/app/src/main/java/org/typesense/samplekotlin/data/repository/TypesenseBookRepository.kt create mode 100644 typesense-kotlin/app/src/main/java/org/typesense/samplekotlin/domain/model/Book.kt create mode 100644 typesense-kotlin/app/src/main/java/org/typesense/samplekotlin/domain/repository/BookRepository.kt create mode 100644 typesense-kotlin/app/src/main/java/org/typesense/samplekotlin/domain/usecase/SearchBooksUseCase.kt create mode 100644 typesense-kotlin/app/src/main/java/org/typesense/samplekotlin/presentation/BookAdapter.kt create mode 100644 typesense-kotlin/app/src/main/java/org/typesense/samplekotlin/presentation/BookViewModel.kt create mode 100644 typesense-kotlin/app/src/main/java/org/typesense/samplekotlin/presentation/MainActivity.kt create mode 100644 typesense-kotlin/app/src/main/res/drawable/badge_bg.xml create mode 100644 typesense-kotlin/app/src/main/res/drawable/ic_kotlin_logo.xml create mode 100644 typesense-kotlin/app/src/main/res/drawable/ic_launcher_background.xml create mode 100644 typesense-kotlin/app/src/main/res/drawable/ic_launcher_foreground.xml create mode 100644 typesense-kotlin/app/src/main/res/drawable/search_bg.xml create mode 100644 typesense-kotlin/app/src/main/res/layout/activity_main.xml create mode 100644 typesense-kotlin/app/src/main/res/layout/item_book.xml create mode 100644 typesense-kotlin/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml create mode 100644 typesense-kotlin/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml create mode 100644 typesense-kotlin/app/src/main/res/mipmap-hdpi/ic_launcher.webp create mode 100644 typesense-kotlin/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp create mode 100644 typesense-kotlin/app/src/main/res/mipmap-mdpi/ic_launcher.webp create mode 100644 typesense-kotlin/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp create mode 100644 typesense-kotlin/app/src/main/res/mipmap-xhdpi/ic_launcher.webp create mode 100644 typesense-kotlin/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp create mode 100644 typesense-kotlin/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp create mode 100644 typesense-kotlin/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp create mode 100644 typesense-kotlin/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp create mode 100644 typesense-kotlin/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp create mode 100644 typesense-kotlin/app/src/main/res/values-night/themes.xml create mode 100644 typesense-kotlin/app/src/main/res/values/colors.xml create mode 100644 typesense-kotlin/app/src/main/res/values/strings.xml create mode 100644 typesense-kotlin/app/src/main/res/values/themes.xml create mode 100644 typesense-kotlin/app/src/main/res/xml/backup_rules.xml create mode 100644 typesense-kotlin/app/src/main/res/xml/data_extraction_rules.xml create mode 100644 typesense-kotlin/app/src/test/java/org/typesense/samplekotlin/ExampleUnitTest.kt create mode 100644 typesense-kotlin/build.gradle.kts create mode 100644 typesense-kotlin/gradle.properties create mode 100644 typesense-kotlin/gradle/libs.versions.toml create mode 100644 typesense-kotlin/gradle/wrapper/gradle-wrapper.jar create mode 100644 typesense-kotlin/gradle/wrapper/gradle-wrapper.properties create mode 100755 typesense-kotlin/gradlew create mode 100644 typesense-kotlin/gradlew.bat create mode 100644 typesense-kotlin/settings.gradle.kts diff --git a/typesense-kotlin/.gitignore b/typesense-kotlin/.gitignore new file mode 100644 index 0000000..aa724b7 --- /dev/null +++ b/typesense-kotlin/.gitignore @@ -0,0 +1,15 @@ +*.iml +.gradle +/local.properties +/.idea/caches +/.idea/libraries +/.idea/modules.xml +/.idea/workspace.xml +/.idea/navEditor.xml +/.idea/assetWizardSettings.xml +.DS_Store +/build +/captures +.externalNativeBuild +.cxx +local.properties diff --git a/typesense-kotlin/app/.gitignore b/typesense-kotlin/app/.gitignore new file mode 100644 index 0000000..42afabf --- /dev/null +++ b/typesense-kotlin/app/.gitignore @@ -0,0 +1 @@ +/build \ No newline at end of file diff --git a/typesense-kotlin/app/build.gradle.kts b/typesense-kotlin/app/build.gradle.kts new file mode 100644 index 0000000..f34802e --- /dev/null +++ b/typesense-kotlin/app/build.gradle.kts @@ -0,0 +1,54 @@ +plugins { + alias(libs.plugins.android.application) + alias(libs.plugins.kotlin.android) +} + +android { + namespace = "org.typesense.samplekotlin" + compileSdk = 34 + + defaultConfig { + applicationId = "org.typesense.samplekotlin" + minSdk = 26 + targetSdk = 34 + versionCode = 1 + versionName = "1.0" + + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + } + + buildTypes { + release { + isMinifyEnabled = false + proguardFiles( + getDefaultProguardFile("proguard-android-optimize.txt"), + "proguard-rules.pro" + ) + } + } + compileOptions { + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 + } + kotlinOptions { + jvmTarget = "11" + } + buildFeatures { + viewBinding = true + } +} + +dependencies { + implementation(libs.androidx.core.ktx) + implementation(libs.androidx.appcompat) + implementation(libs.material) + implementation(libs.typesense) + implementation(libs.androidx.lifecycle.viewmodel.ktx) + implementation(libs.androidx.lifecycle.runtime.ktx) + implementation(libs.kotlinx.coroutines.android) + implementation(libs.coil) + + testImplementation(libs.junit) + androidTestImplementation(libs.androidx.junit) + androidTestImplementation(libs.androidx.espresso.core) +} diff --git a/typesense-kotlin/app/proguard-rules.pro b/typesense-kotlin/app/proguard-rules.pro new file mode 100644 index 0000000..481bb43 --- /dev/null +++ b/typesense-kotlin/app/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile \ No newline at end of file diff --git a/typesense-kotlin/app/src/androidTest/java/org/typesense/samplekotlin/ExampleInstrumentedTest.kt b/typesense-kotlin/app/src/androidTest/java/org/typesense/samplekotlin/ExampleInstrumentedTest.kt new file mode 100644 index 0000000..081eaf1 --- /dev/null +++ b/typesense-kotlin/app/src/androidTest/java/org/typesense/samplekotlin/ExampleInstrumentedTest.kt @@ -0,0 +1,24 @@ +package org.typesense.samplekotlin + +import androidx.test.platform.app.InstrumentationRegistry +import androidx.test.ext.junit.runners.AndroidJUnit4 + +import org.junit.Test +import org.junit.runner.RunWith + +import org.junit.Assert.* + +/** + * Instrumented test, which will execute on an Android device. + * + * See [testing documentation](http://d.android.com/tools/testing). + */ +@RunWith(AndroidJUnit4::class) +class ExampleInstrumentedTest { + @Test + fun useAppContext() { + // Context of the app under test. + val appContext = InstrumentationRegistry.getInstrumentation().targetContext + assertEquals("org.typesense.samplekotlin", appContext.packageName) + } +} \ No newline at end of file diff --git a/typesense-kotlin/app/src/main/AndroidManifest.xml b/typesense-kotlin/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..ba2e1dd --- /dev/null +++ b/typesense-kotlin/app/src/main/AndroidManifest.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + diff --git a/typesense-kotlin/app/src/main/java/org/typesense/samplekotlin/data/repository/TypesenseBookRepository.kt b/typesense-kotlin/app/src/main/java/org/typesense/samplekotlin/data/repository/TypesenseBookRepository.kt new file mode 100644 index 0000000..0e2617b --- /dev/null +++ b/typesense-kotlin/app/src/main/java/org/typesense/samplekotlin/data/repository/TypesenseBookRepository.kt @@ -0,0 +1,32 @@ +package org.typesense.samplekotlin.data.repository + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import org.typesense.api.Client +import org.typesense.model.SearchParameters +import org.typesense.samplekotlin.domain.model.Book +import org.typesense.samplekotlin.domain.repository.BookRepository + +class TypesenseBookRepository(private val client: Client) : BookRepository { + + override suspend fun searchBooks(query: String): List = withContext(Dispatchers.IO) { + val searchParameters = SearchParameters() + .q(query) + .queryBy("title,authors") + .sortBy("average_rating:desc") + + val searchResult = client.collections("books").documents().search(searchParameters) + + searchResult.hits?.map { hit -> + val document = hit.document + Book( + id = document["id"]?.toString() ?: "", + title = document["title"]?.toString() ?: "", + authors = (document["authors"] as? List<*>)?.map { it.toString() } ?: emptyList(), + publicationYear = (document["publication_year"] as? Double)?.toInt(), + imageUrl = document["image_url"]?.toString(), + averageRating = document["average_rating"] as? Double + ) + } ?: emptyList() + } +} diff --git a/typesense-kotlin/app/src/main/java/org/typesense/samplekotlin/domain/model/Book.kt b/typesense-kotlin/app/src/main/java/org/typesense/samplekotlin/domain/model/Book.kt new file mode 100644 index 0000000..798946a --- /dev/null +++ b/typesense-kotlin/app/src/main/java/org/typesense/samplekotlin/domain/model/Book.kt @@ -0,0 +1,10 @@ +package org.typesense.samplekotlin.domain.model + +data class Book( + val id: String, + val title: String, + val authors: List, + val publicationYear: Int?, + val imageUrl: String?, + val averageRating: Double? +) diff --git a/typesense-kotlin/app/src/main/java/org/typesense/samplekotlin/domain/repository/BookRepository.kt b/typesense-kotlin/app/src/main/java/org/typesense/samplekotlin/domain/repository/BookRepository.kt new file mode 100644 index 0000000..e445642 --- /dev/null +++ b/typesense-kotlin/app/src/main/java/org/typesense/samplekotlin/domain/repository/BookRepository.kt @@ -0,0 +1,7 @@ +package org.typesense.samplekotlin.domain.repository + +import org.typesense.samplekotlin.domain.model.Book + +interface BookRepository { + suspend fun searchBooks(query: String): List +} diff --git a/typesense-kotlin/app/src/main/java/org/typesense/samplekotlin/domain/usecase/SearchBooksUseCase.kt b/typesense-kotlin/app/src/main/java/org/typesense/samplekotlin/domain/usecase/SearchBooksUseCase.kt new file mode 100644 index 0000000..ac81c10 --- /dev/null +++ b/typesense-kotlin/app/src/main/java/org/typesense/samplekotlin/domain/usecase/SearchBooksUseCase.kt @@ -0,0 +1,18 @@ +package org.typesense.samplekotlin.domain.usecase + +import org.typesense.samplekotlin.domain.model.Book +import org.typesense.samplekotlin.domain.repository.BookRepository + +class SearchBooksUseCase(private val repository: BookRepository) { + suspend operator fun invoke(query: String): Result> { + return try { + if (query.isBlank()) { + Result.success(emptyList()) + } else { + Result.success(repository.searchBooks(query)) + } + } catch (e: Exception) { + Result.failure(e) + } + } +} diff --git a/typesense-kotlin/app/src/main/java/org/typesense/samplekotlin/presentation/BookAdapter.kt b/typesense-kotlin/app/src/main/java/org/typesense/samplekotlin/presentation/BookAdapter.kt new file mode 100644 index 0000000..1a9c3e5 --- /dev/null +++ b/typesense-kotlin/app/src/main/java/org/typesense/samplekotlin/presentation/BookAdapter.kt @@ -0,0 +1,42 @@ +package org.typesense.samplekotlin.presentation + +import android.view.LayoutInflater +import android.view.ViewGroup +import androidx.recyclerview.widget.DiffUtil +import androidx.recyclerview.widget.ListAdapter +import androidx.recyclerview.widget.RecyclerView +import coil.load +import org.typesense.samplekotlin.databinding.ItemBookBinding +import org.typesense.samplekotlin.domain.model.Book + +class BookAdapter : ListAdapter(BookDiffCallback()) { + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BookViewHolder { + val binding = ItemBookBinding.inflate(LayoutInflater.from(parent.context), parent, false) + return BookViewHolder(binding) + } + + override fun onBindViewHolder(holder: BookViewHolder, position: Int) { + holder.bind(getItem(position)) + } + + class BookViewHolder(private val binding: ItemBookBinding) : RecyclerView.ViewHolder(binding.root) { + fun bind(book: Book) { + binding.titleTextView.text = book.title + binding.authorsTextView.text = book.authors.joinToString(", ") + binding.yearTextView.text = book.publicationYear?.toString() ?: "" + binding.ratingBar.rating = book.averageRating?.toFloat() ?: 0f + + binding.bookCoverImageView.load(book.imageUrl) { + crossfade(true) + placeholder(android.R.color.darker_gray) + error(android.R.color.darker_gray) + } + } + } + + class BookDiffCallback : DiffUtil.ItemCallback() { + override fun areItemsTheSame(oldItem: Book, newItem: Book): Boolean = oldItem.id == newItem.id + override fun areContentsTheSame(oldItem: Book, newItem: Book): Boolean = oldItem == newItem + } +} diff --git a/typesense-kotlin/app/src/main/java/org/typesense/samplekotlin/presentation/BookViewModel.kt b/typesense-kotlin/app/src/main/java/org/typesense/samplekotlin/presentation/BookViewModel.kt new file mode 100644 index 0000000..ae94764 --- /dev/null +++ b/typesense-kotlin/app/src/main/java/org/typesense/samplekotlin/presentation/BookViewModel.kt @@ -0,0 +1,40 @@ +package org.typesense.samplekotlin.presentation + +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.launch +import org.typesense.samplekotlin.domain.model.Book +import org.typesense.samplekotlin.domain.usecase.SearchBooksUseCase + +class BookViewModel(private val searchBooksUseCase: SearchBooksUseCase) : ViewModel() { + + private val _uiState = MutableStateFlow(BookUiState.Idle) + val uiState: StateFlow = _uiState + + fun search(query: String) { + if (query.isBlank()) { + _uiState.value = BookUiState.Idle + return + } + + _uiState.value = BookUiState.Loading + viewModelScope.launch { + searchBooksUseCase(query) + .onSuccess { books -> + _uiState.value = BookUiState.Success(books) + } + .onFailure { error -> + _uiState.value = BookUiState.Error(error.message ?: "Unknown error") + } + } + } +} + +sealed class BookUiState { + object Idle : BookUiState() + object Loading : BookUiState() + data class Success(val books: List) : BookUiState() + data class Error(val message: String) : BookUiState() +} diff --git a/typesense-kotlin/app/src/main/java/org/typesense/samplekotlin/presentation/MainActivity.kt b/typesense-kotlin/app/src/main/java/org/typesense/samplekotlin/presentation/MainActivity.kt new file mode 100644 index 0000000..92194f0 --- /dev/null +++ b/typesense-kotlin/app/src/main/java/org/typesense/samplekotlin/presentation/MainActivity.kt @@ -0,0 +1,105 @@ +package org.typesense.samplekotlin.presentation + +import android.os.Bundle +import android.view.View +import android.widget.Toast +import androidx.appcompat.app.AppCompatActivity +import androidx.core.widget.addTextChangedListener +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.ViewModel +import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.lifecycleScope +import androidx.lifecycle.repeatOnLifecycle +import androidx.recyclerview.widget.GridLayoutManager +import androidx.recyclerview.widget.LinearLayoutManager +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import org.typesense.api.Client +import org.typesense.api.Configuration +import org.typesense.resources.Node +import org.typesense.samplekotlin.data.repository.TypesenseBookRepository +import org.typesense.samplekotlin.databinding.ActivityMainBinding +import org.typesense.samplekotlin.domain.usecase.SearchBooksUseCase +import java.time.Duration + +class MainActivity : AppCompatActivity() { + + private lateinit var binding: ActivityMainBinding + private lateinit var viewModel: BookViewModel + private var searchJob: Job? = null + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + binding = ActivityMainBinding.inflate(layoutInflater) + setContentView(binding.root) + + setupViewModel() + setupRecyclerView() + setupSearch() + observeUiState() + + // Initial search to show all books + viewModel.search("*") + } + + private fun setupViewModel() { + // Local Typesense configuration + // 10.0.2.2 is the special IP address to access the host machine from the Android emulator. + // If you are using a physical device, use your machine's local IP (e.g., 192.168.1.x). + val nodes = listOf(Node("http", "10.0.2.2", "8108")) + val configuration = Configuration(nodes, Duration.ofSeconds(2), "xyz") + val client = Client(configuration) + + val repository = TypesenseBookRepository(client) + val useCase = SearchBooksUseCase(repository) + + viewModel = ViewModelProvider(this, object : ViewModelProvider.Factory { + override fun create(modelClass: Class): T { + @Suppress("UNCHECKED_CAST") + return BookViewModel(useCase) as T + } + })[BookViewModel::class.java] + } + + private fun setupRecyclerView() { + val adapter = BookAdapter() + binding.recyclerView.layoutManager = GridLayoutManager(this, 2) + binding.recyclerView.adapter = adapter + } + + private fun setupSearch() { + binding.searchEditText.addTextChangedListener { text -> + searchJob?.cancel() + searchJob = lifecycleScope.launch { + delay(300) // Debounce search + viewModel.search(text?.toString() ?: " ") + } + } + } + + private fun observeUiState() { + lifecycleScope.launch { + repeatOnLifecycle(Lifecycle.State.STARTED) { + viewModel.uiState.collect { state -> + when (state) { + is BookUiState.Idle -> { + binding.progressBar.visibility = View.GONE + } + is BookUiState.Loading -> { + binding.progressBar.visibility = View.VISIBLE + } + is BookUiState.Success -> { + binding.progressBar.visibility = View.GONE + (binding.recyclerView.adapter as BookAdapter).submitList(state.books) + } + is BookUiState.Error -> { + binding.progressBar.visibility = View.GONE + Toast.makeText(this@MainActivity, state.message, Toast.LENGTH_SHORT).show() + } + } + } + } + } + } +} diff --git a/typesense-kotlin/app/src/main/res/drawable/badge_bg.xml b/typesense-kotlin/app/src/main/res/drawable/badge_bg.xml new file mode 100644 index 0000000..447fd04 --- /dev/null +++ b/typesense-kotlin/app/src/main/res/drawable/badge_bg.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/typesense-kotlin/app/src/main/res/drawable/ic_kotlin_logo.xml b/typesense-kotlin/app/src/main/res/drawable/ic_kotlin_logo.xml new file mode 100644 index 0000000..c652e83 --- /dev/null +++ b/typesense-kotlin/app/src/main/res/drawable/ic_kotlin_logo.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/typesense-kotlin/app/src/main/res/drawable/ic_launcher_background.xml b/typesense-kotlin/app/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000..07d5da9 --- /dev/null +++ b/typesense-kotlin/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,170 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/typesense-kotlin/app/src/main/res/drawable/ic_launcher_foreground.xml b/typesense-kotlin/app/src/main/res/drawable/ic_launcher_foreground.xml new file mode 100644 index 0000000..2b068d1 --- /dev/null +++ b/typesense-kotlin/app/src/main/res/drawable/ic_launcher_foreground.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/typesense-kotlin/app/src/main/res/drawable/search_bg.xml b/typesense-kotlin/app/src/main/res/drawable/search_bg.xml new file mode 100644 index 0000000..0f25174 --- /dev/null +++ b/typesense-kotlin/app/src/main/res/drawable/search_bg.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/typesense-kotlin/app/src/main/res/layout/activity_main.xml b/typesense-kotlin/app/src/main/res/layout/activity_main.xml new file mode 100644 index 0000000..f62c7af --- /dev/null +++ b/typesense-kotlin/app/src/main/res/layout/activity_main.xml @@ -0,0 +1,97 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/typesense-kotlin/app/src/main/res/layout/item_book.xml b/typesense-kotlin/app/src/main/res/layout/item_book.xml new file mode 100644 index 0000000..8742957 --- /dev/null +++ b/typesense-kotlin/app/src/main/res/layout/item_book.xml @@ -0,0 +1,71 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/typesense-kotlin/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/typesense-kotlin/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 0000000..6f3b755 --- /dev/null +++ b/typesense-kotlin/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/typesense-kotlin/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/typesense-kotlin/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 0000000..6f3b755 --- /dev/null +++ b/typesense-kotlin/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/typesense-kotlin/app/src/main/res/mipmap-hdpi/ic_launcher.webp b/typesense-kotlin/app/src/main/res/mipmap-hdpi/ic_launcher.webp new file mode 100644 index 0000000000000000000000000000000000000000..c209e78ecd372343283f4157dcfd918ec5165bb3 GIT binary patch literal 1404 zcmV-?1%vuhNk&F=1pok7MM6+kP&il$0000G0000-002h-06|PpNX!5L00Dqw+t%{r zzW2vH!KF=w&cMnnN@{whkTw+#mAh0SV?YL=)3MimFYCWp#fpdtz~8$hD5VPuQgtcN zXl<@<#Cme5f5yr2h%@8TWh?)bSK`O z^Z@d={gn7J{iyxL_y_%J|L>ep{dUxUP8a{byupH&!UNR*OutO~0{*T4q5R6@ApLF! z5{w?Z150gC7#>(VHFJZ-^6O@PYp{t!jH(_Z*nzTK4 zkc{fLE4Q3|mA2`CWQ3{8;gxGizgM!zccbdQoOLZc8hThi-IhN90RFT|zlxh3Ty&VG z?Fe{#9RrRnxzsu|Lg2ddugg7k%>0JeD+{XZ7>Z~{=|M+sh1MF7~ zz>To~`~LVQe1nNoR-gEzkpe{Ak^7{{ZBk2i_<+`Bq<^GB!RYG+z)h;Y3+<{zlMUYd zrd*W4w&jZ0%kBuDZ1EW&KLpyR7r2=}fF2%0VwHM4pUs}ZI2egi#DRMYZPek*^H9YK zay4Iy3WXFG(F14xYsoDA|KXgGc5%2DhmQ1gFCkrgHBm!lXG8I5h*uf{rn48Z!_@ z4Bk6TJAB2CKYqPjiX&mWoW>OPFGd$wqroa($ne7EUK;#3VYkXaew%Kh^3OrMhtjYN?XEoY`tRPQsAkH-DSL^QqyN0>^ zmC>{#F14jz4GeW{pJoRpLFa_*GI{?T93^rX7SPQgT@LbLqpNA}<@2wH;q493)G=1Y z#-sCiRNX~qf3KgiFzB3I>4Z%AfS(3$`-aMIBU+6?gbgDb!)L~A)je+;fR0jWLL-Fu z4)P{c7{B4Hp91&%??2$v9iRSFnuckHUm}or9seH6 z>%NbT+5*@L5(I9j@06@(!{ZI?U0=pKn8uwIg&L{JV14+8s2hnvbRrU|hZCd}IJu7*;;ECgO%8_*W Kmw_-CKmY()leWbG literal 0 HcmV?d00001 diff --git a/typesense-kotlin/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp b/typesense-kotlin/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp new file mode 100644 index 0000000000000000000000000000000000000000..b2dfe3d1ba5cf3ee31b3ecc1ced89044a1f3b7a9 GIT binary patch literal 2898 zcmV-Y3$650Nk&FW3jhFDMM6+kP&il$0000G0000-002h-06|PpNWB9900E$G+qN-D z+81ABX7q?;bwx%xBg?kcwr$(C-Tex-ZCkHUw(Y9#+`E5-zuONG5fgw~E2WDng@Bc@ z24xy+R1n%~6xI#u9vJ8zREI)sb<&Il(016}Z~V1n^PU3-_H17A*Bf^o)&{_uBv}Py zulRfeE8g(g6HFhk_?o_;0@tz?1I+l+Y#Q*;RVC?(ud`_cU-~n|AX-b`JHrOIqn(-t&rOg-o`#C zh0LPxmbOAEb;zHTu!R3LDh1QO zZTf-|lJNUxi-PpcbRjw3n~n-pG;$+dIF6eqM5+L();B2O2tQ~|p{PlpNcvDbd1l%c zLtXn%lu(3!aNK!V#+HNn_D3lp z2%l+hK-nsj|Bi9;V*WIcQRTt5j90A<=am+cc`J zTYIN|PsYAhJ|=&h*4wI4ebv-C=Be#u>}%m;a{IGmJDU`0snWS&$9zdrT(z8#{OZ_Y zxwJx!ZClUi%YJjD6Xz@OP8{ieyJB=tn?>zaI-4JN;rr`JQbb%y5h2O-?_V@7pG_+y z(lqAsqYr!NyVb0C^|uclHaeecG)Sz;WV?rtoqOdAAN{j%?Uo%owya(F&qps@Id|Of zo@~Y-(Ymf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{mGkyA`+Gwd4D-^1qtNTUK)`N*=NTG-6}=5k6suNfdLt*dt8D| z%H#$k)z#ZRcf|zDWB|pn<3+7Nz>?WW9WdkO5(a^m+D4WRJ9{wc>Y}IN)2Kbgn;_O? zGqdr&9~|$Y0tP=N(k7^Eu;iO*w+f%W`20BNo)=Xa@M_)+o$4LXJyiw{F?a633SC{B zl~9FH%?^Rm*LVz`lkULs)%idDX^O)SxQol(3jDRyBVR!7d`;ar+D7do)jQ}m`g$TevUD5@?*P8)voa?kEe@_hl{_h8j&5eB-5FrYW&*FHVt$ z$kRF9Nstj%KRzpjdd_9wO=4zO8ritN*NPk_9avYrsF(!4))tm{Ga#OY z(r{0buexOzu7+rw8E08Gxd`LTOID{*AC1m*6Nw@osfB%0oBF5sf<~wH1kL;sd zo)k6^VyRFU`)dt*iX^9&QtWbo6yE8XXH?`ztvpiOLgI3R+=MOBQ9=rMVgi<*CU%+d1PQQ0a1U=&b0vkF207%xU0ssI2 literal 0 HcmV?d00001 diff --git a/typesense-kotlin/app/src/main/res/mipmap-mdpi/ic_launcher.webp b/typesense-kotlin/app/src/main/res/mipmap-mdpi/ic_launcher.webp new file mode 100644 index 0000000000000000000000000000000000000000..4f0f1d64e58ba64d180ce43ee13bf9a17835fbca GIT binary patch literal 982 zcmV;{11bDcNk&G_0{{S5MM6+kP&il$0000G0000l001ul06|PpNU8t;00Dqo+t#w^ z^1csucXz7-Qrhzl9HuHB%l>&>1tG2^vb*E&k^T3$FG1eQZ51g$uv4V+kI`0<^1Z@N zk?Jjh$olyC%l>)Xq;7!>{iBj&BjJ`P&$fsCfpve_epJOBkTF?nu-B7D!hO=2ZR}

C%4 zc_9eOXvPbC4kzU8YowIA8cW~Uv|eB&yYwAObSwL2vY~UYI7NXPvf3b+c^?wcs~_t{ ze_m66-0)^{JdOMKPwjpQ@Sna!*?$wTZ~su*tNv7o!gXT!GRgivP}ec?5>l1!7<(rT zds|8x(qGc673zrvYIz;J23FG{9nHMnAuP}NpAED^laz3m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*6_GjYD};Squ83<_?^SbALb{a`j<0Gn%6JY!zhp=Fg}Ga2|8 z52e1WU%^L1}15Ex0fF$e@eCT(()_P zvV?CA%#Sy08_U6VPt4EtmVQraWJX` zh=N|WQ>LgrvF~R&qOfB$!%D3cGv?;Xh_z$z7k&s4N)$WYf*k=|*jCEkO19{h_(%W4 zPuOqbCw`SeAX*R}UUsbVsgtuG?xs(#Ikx9`JZoQFz0n*7ZG@Fv@kZk`gzO$HoA9kN z8U5{-yY zvV{`&WKU2$mZeoBmiJrEdzUZAv1sRxpePdg1)F*X^Y)zp^Y*R;;z~vOv-z&)&G)JQ{m!C9cmziu1^nHA z`#`0c>@PnQ9CJKgC5NjJD8HM3|KC(g5nnCq$n0Gsu_DXk36@ql%npEye|?%RmG)

FJ$wK}0tWNB{uH;AM~i literal 0 HcmV?d00001 diff --git a/typesense-kotlin/app/src/main/res/mipmap-xhdpi/ic_launcher.webp b/typesense-kotlin/app/src/main/res/mipmap-xhdpi/ic_launcher.webp new file mode 100644 index 0000000000000000000000000000000000000000..948a3070fe34c611c42c0d3ad3013a0dce358be0 GIT binary patch literal 1900 zcmV-y2b1_xNk&Fw2LJ$9MM6+kP&il$0000G0001A003VA06|PpNH75a00DqwTbm-~ zullQTcXxO9ki!OCRx^i?oR|n!<8G0=kI^!JSjFi-LL*`V;ET0H2IXfU0*i>o6o6Gy zRq6Ap5(_{XLdXcL-MzlN`ugSdZY_`jXhcENAu)N_0?GhF))9R;E`!bo9p?g?SRgw_ zEXHhFG$0{qYOqhdX<(wE4N@es3VIo$%il%6xP9gjiBri+2pI6aY4 zJbgh-Ud|V%3O!IcHKQx1FQH(_*TK;1>FQWbt^$K1zNn^cczkBs=QHCYZ8b&l!UV{K z{L0$KCf_&KR^}&2Fe|L&?1I7~pBENnCtCuH3sjcx6$c zwqkNkru);ie``q+_QI;IYLD9OV0ZxkuyBz|5<$1BH|vtey$> z5oto4=l-R-Aaq`Dk0}o9N0VrkqW_#;!u{!bJLDq%0092{Gh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aLt+ZL(g;n$Dzy5=m=_TV(3H8^C{r0xd zp#a%}ht55dOq?yhwYPrtp-m1xXp;4X;)NhxxUpgP%XTLmO zcjaFva^}dP3$&sfFTIR_jC=2pHh9kpI@2(6V*GQo7Ws)`j)hd+tr@P~gR*2gO@+1? zG<`_tB+LJuF|SZ9tIec;h%}}6WClT`L>HSW?E{Hp1h^+mlbf_$9zA>!ug>NALJsO{ mU%z=YwVD?}XMya)Bp;vlyE5&E_6!fzx9pwrdz474!~g(M6R?N? literal 0 HcmV?d00001 diff --git a/typesense-kotlin/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp b/typesense-kotlin/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp new file mode 100644 index 0000000000000000000000000000000000000000..1b9a6956b3acdc11f40ce2bb3f6efbd845cc243f GIT binary patch literal 3918 zcmV-U53%r4Nk&FS4*&pHMM6+kP&il$0000G0001A003VA06|PpNSy@$00HoY|G(*G z+qV7x14$dSO^Re!iqt-AAIE9iwr$(CZQJL$blA4B`>;C3fBY6Q8_YSjb2%a=fc}4E zrSzssacq<^nmW|Rs93PJni30R<8w<(bK_$LO4L?!_OxLl$}K$MUEllnMK|rg=f3;y z*?;3j|Nh>)p0JQ3A~rf(MibH2r+)3cyV1qF&;8m{w-S*y+0mM){KTK^M5}ksc`qX3 zy>rf^b>~l>SSHds8(I@hz3&PD@LmEs4&prkT=BjsBCXTMhN$_)+kvnl0bLKW5rEsj z*d#KXGDB4P&>etx0X+`R19yC=LS)j!mgs5M0L~+o-T~Jl!p!AJxnGAhV%~rhYUL4hlWhgES3Kb5oA&X z{}?3OBSS-{!v$nCIGj->(-TAG)8LR{htr41^gxsT8yqt2@DEG6Yl`Uma3Nd4;YUoW zTbkYl3CMU5ypMF3EIkYmWL|*BknM`0+Kq6CpvO(y$#j94e+q{vI{Zp8cV_6RK!`&C zob$*5Q|$IZ09dW=L!V zw@#2wviu|<#3lgGE8GEhcx+zBt`} zOwP8j9X%^f7i_bth4PiJ$LY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3e@jNfMj?jHV$MWjk!DDKP zkAz$Y?Sr)!GUOX}qTQ5aMh|wq1uq}~joWyKl=b_LboM#wi{CMuz5x6BKlA-qy++cM01D3b7`uD z#l6M4pI;JCypO8JZ6?U&wNxR!{4oB_ zlV!x9+-&Qy6{%MQ{~yoZGkKiTSC`YS_j22~G;xUV855g2&C(zm^V!(wpcm@zn{%!g z4}JGo(sGZ1O~to-}le

UmY2RIYtNPVDpE$%vda+HD#3m z&VuXJ{BK&Qe+rBa7eq}Q(bq|tn(RrJAk|ztj2(i{d>nmQnM?;HF2k&9sA6up5tmjl z7lySlzMbifH17-m-Lwa_F&e7nOH?ESi3#ckR3tsM+jsck3`oG!uMS}|eAwVXv>}qxwq?QY%QJ0}r@^;fhuUA9W z*BVl>TGo&N004@xSiwDUXUvp51sVmqO3m)=B55aPwf@0=e}cN+$-BdKxY`YrT_4)0 z_d10#i44Q*rFr8MC>*)v$EJvz``(pb{e&*6k+b zsMz%($|1+8hn8c2?P(l@;Rb&CsZeYoCI3?2!LqjbwPXW3z4G$Qfj=cT5Yb%vY0(AX oeb?AaKtwrnc|$|zzw9vfvn^aJJ!zd)XFXqqy0000001=f@-~a#s literal 0 HcmV?d00001 diff --git a/typesense-kotlin/app/src/main/res/values-night/themes.xml b/typesense-kotlin/app/src/main/res/values-night/themes.xml new file mode 100644 index 0000000..0883fc5 --- /dev/null +++ b/typesense-kotlin/app/src/main/res/values-night/themes.xml @@ -0,0 +1,17 @@ + + + + \ No newline at end of file diff --git a/typesense-kotlin/app/src/main/res/values/colors.xml b/typesense-kotlin/app/src/main/res/values/colors.xml new file mode 100644 index 0000000..1916832 --- /dev/null +++ b/typesense-kotlin/app/src/main/res/values/colors.xml @@ -0,0 +1,14 @@ + + + #1A1A1A + #2A2A2A + #333333 + #FFFFFF + #B0B0B0 + #808080 + #EF5350 + #61DAFB + #7F52FF + #FF000000 + #FFFFFFFF + \ No newline at end of file diff --git a/typesense-kotlin/app/src/main/res/values/strings.xml b/typesense-kotlin/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..54b2402 --- /dev/null +++ b/typesense-kotlin/app/src/main/res/values/strings.xml @@ -0,0 +1,3 @@ + + Typesense with Kotlin + \ No newline at end of file diff --git a/typesense-kotlin/app/src/main/res/values/themes.xml b/typesense-kotlin/app/src/main/res/values/themes.xml new file mode 100644 index 0000000..0883fc5 --- /dev/null +++ b/typesense-kotlin/app/src/main/res/values/themes.xml @@ -0,0 +1,17 @@ + + + + \ No newline at end of file diff --git a/typesense-kotlin/app/src/main/res/xml/backup_rules.xml b/typesense-kotlin/app/src/main/res/xml/backup_rules.xml new file mode 100644 index 0000000..4df9255 --- /dev/null +++ b/typesense-kotlin/app/src/main/res/xml/backup_rules.xml @@ -0,0 +1,13 @@ + + + + \ No newline at end of file diff --git a/typesense-kotlin/app/src/main/res/xml/data_extraction_rules.xml b/typesense-kotlin/app/src/main/res/xml/data_extraction_rules.xml new file mode 100644 index 0000000..9ee9997 --- /dev/null +++ b/typesense-kotlin/app/src/main/res/xml/data_extraction_rules.xml @@ -0,0 +1,19 @@ + + + + + + + \ No newline at end of file diff --git a/typesense-kotlin/app/src/test/java/org/typesense/samplekotlin/ExampleUnitTest.kt b/typesense-kotlin/app/src/test/java/org/typesense/samplekotlin/ExampleUnitTest.kt new file mode 100644 index 0000000..fdbc6af --- /dev/null +++ b/typesense-kotlin/app/src/test/java/org/typesense/samplekotlin/ExampleUnitTest.kt @@ -0,0 +1,17 @@ +package org.typesense.samplekotlin + +import org.junit.Test + +import org.junit.Assert.* + +/** + * Example local unit test, which will execute on the development machine (host). + * + * See [testing documentation](http://d.android.com/tools/testing). + */ +class ExampleUnitTest { + @Test + fun addition_isCorrect() { + assertEquals(4, 2 + 2) + } +} \ No newline at end of file diff --git a/typesense-kotlin/build.gradle.kts b/typesense-kotlin/build.gradle.kts new file mode 100644 index 0000000..7f09f7c --- /dev/null +++ b/typesense-kotlin/build.gradle.kts @@ -0,0 +1,5 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. +plugins { + alias(libs.plugins.android.application) apply false + alias(libs.plugins.kotlin.android) apply false +} diff --git a/typesense-kotlin/gradle.properties b/typesense-kotlin/gradle.properties new file mode 100644 index 0000000..20e2a01 --- /dev/null +++ b/typesense-kotlin/gradle.properties @@ -0,0 +1,23 @@ +# Project-wide Gradle settings. +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. For more details, visit +# https://developer.android.com/r/tools/gradle-multi-project-decoupled-projects +# org.gradle.parallel=true +# AndroidX package structure to make it clearer which packages are bundled with the +# Android operating system, and which are packaged with your app's APK +# https://developer.android.com/topic/libraries/support-library/androidx-rn +android.useAndroidX=true +# Kotlin code style for this project: "official" or "obsolete": +kotlin.code.style=official +# Enables namespacing of each library's R class so that its R class includes only the +# resources declared in the library itself and none from the library's dependencies, +# thereby reducing the size of the R class for that library +android.nonTransitiveRClass=true \ No newline at end of file diff --git a/typesense-kotlin/gradle/libs.versions.toml b/typesense-kotlin/gradle/libs.versions.toml new file mode 100644 index 0000000..13066c9 --- /dev/null +++ b/typesense-kotlin/gradle/libs.versions.toml @@ -0,0 +1,30 @@ +[versions] +agp = "8.3.2" +kotlin = "1.9.22" +coreKtx = "1.12.0" +junit = "4.13.2" +junitVersion = "1.1.5" +espressoCore = "3.5.1" +appcompat = "1.6.1" +material = "1.11.0" +typesense = "2.1.0" +lifecycle = "2.6.2" +coroutines = "1.7.3" +coil = "2.6.0" + +[libraries] +androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" } +junit = { group = "junit", name = "junit", version.ref = "junit" } +androidx-junit = { group = "androidx.test.ext", name = "junit", version.ref = "junitVersion" } +androidx-espresso-core = { group = "androidx.test.espresso", name = "espresso-core", version.ref = "espressoCore" } +androidx-appcompat = { group = "androidx.appcompat", name = "appcompat", version.ref = "appcompat" } +material = { group = "com.google.android.material", name = "material", version.ref = "material" } +typesense = { group = "org.typesense", name = "typesense-java", version.ref = "typesense" } +androidx-lifecycle-viewmodel-ktx = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-ktx", version.ref = "lifecycle" } +androidx-lifecycle-runtime-ktx = { group = "androidx.lifecycle", name = "lifecycle-runtime-ktx", version.ref = "lifecycle" } +kotlinx-coroutines-android = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-android", version.ref = "coroutines" } +coil = { group = "io.coil-kt", name = "coil", version.ref = "coil" } + +[plugins] +android-application = { id = "com.android.application", version.ref = "agp" } +kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" } diff --git a/typesense-kotlin/gradle/wrapper/gradle-wrapper.jar b/typesense-kotlin/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..8bdaf60c75ab801e22807dde59e12a8735a34077 GIT binary patch literal 45457 zcma&NW0YlEwk;ePwr$(aux;D69T}N{9ky*d!_2U4+qUuIRNZ#Jck8}7U+vcB{`IjNZqX3eq5;s6ddAkU&5{L|^Ow`ym2B0m+K02+~Q)i807X3X94qi>j)C0e$=H zm31v`=T&y}ACuKx7G~yWSYncG=NFB>O2);i9EmJ(9jSamq?Crj$g~1l3m-4M7;BWn zau2S&sSA0b0Rhg>6YlVLQa;D#)1yw+eGs~36Q$}5?avIRne3TQZXb<^e}?T69w<9~ zUmx1cG0uZ?Kd;Brd$$>r>&MrY*3$t^PWF1+J+G_xmpHW=>mly$<>~wHH+Bt3mzN7W zhR)g{_veH6>*KxLJ~~s{9HZm!UeC86d_>42NRqd$ev8zSMq4kt)q*>8kJ8p|^wuKx zq2Is_HJPoQ_apSoT?zJj7vXBp!xejBc^7F|zU0rhy%Ub*Dy#jJs!>1?CmJ-gulP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ve^~xe_0~x$6h8Q@B_qu#ee=(lkI9@F6$0m=z@H=4&h%Q{htM>uHs(Sr@2ry`fgLA zKj8lVXdGPyy)2J%A${}Rm_a{){wHnlM?yGPQ7#KO{8*(_l0QZHuV};nO?c%h?qwSL z3wem|w*2tdxW5&PxC(Wd0QG_w|GPbw|0UFK`u$~U%!`QKcME;=Q@?*erh4_>FP~1n zAldwG9h$$u_$RFK6Uxo20GHqJzc}Rl-EwVz3h4n z;3~%DwD84i>)-8#&#y3k)3BG5cNaP3?t4q}F%yfv?*yEiC>sSo}$f>nh0QNZXH1N)-Q7kbk=2uL9OrF)nXrE@F1y%_8Yn c82=K%QXLKFx%@O{wJjEi6Y56o#$)Bpeg literal 0 HcmV?d00001 diff --git a/typesense-kotlin/gradle/wrapper/gradle-wrapper.properties b/typesense-kotlin/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..e5cfecc --- /dev/null +++ b/typesense-kotlin/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,9 @@ +#Tue May 12 08:08:11 IST 2026 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionSha256Sum=a17ddd85a26b6a7f5ddb71ff8b05fc5104c0202c6e64782429790c933686c806 +distributionUrl=https\://services.gradle.org/distributions/gradle-9.1.0-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/typesense-kotlin/gradlew b/typesense-kotlin/gradlew new file mode 100755 index 0000000..ef07e01 --- /dev/null +++ b/typesense-kotlin/gradlew @@ -0,0 +1,251 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH="\\\"\\\"" + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/typesense-kotlin/gradlew.bat b/typesense-kotlin/gradlew.bat new file mode 100644 index 0000000..5eed7ee --- /dev/null +++ b/typesense-kotlin/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH= + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/typesense-kotlin/settings.gradle.kts b/typesense-kotlin/settings.gradle.kts new file mode 100644 index 0000000..c6f9110 --- /dev/null +++ b/typesense-kotlin/settings.gradle.kts @@ -0,0 +1,24 @@ +pluginManagement { + repositories { + google { + content { + includeGroupByRegex("com\\.android.*") + includeGroupByRegex("com\\.google.*") + includeGroupByRegex("androidx.*") + } + } + mavenCentral() + gradlePluginPortal() + } +} +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google() + mavenCentral() + } +} + +rootProject.name = "Typesense with Kotlin" +include(":app") + \ No newline at end of file From 0b915d3931a9ae917ec8617c2abcdcd54350699d Mon Sep 17 00:00:00 2001 From: Nikhiladiga Date: Sun, 17 May 2026 22:01:25 +0530 Subject: [PATCH 10/15] First revision: register Kotlin search project in README and rename root project folder --- README.md | 2 ++ .../.gitignore | 0 .../app/.gitignore | 0 .../app/build.gradle.kts | 0 .../app/proguard-rules.pro | 0 .../samplekotlin/ExampleInstrumentedTest.kt | 0 .../app/src/main/AndroidManifest.xml | 0 .../data/repository/TypesenseBookRepository.kt | 0 .../org/typesense/samplekotlin/domain/model/Book.kt | 0 .../domain/repository/BookRepository.kt | 0 .../domain/usecase/SearchBooksUseCase.kt | 0 .../samplekotlin/presentation/BookAdapter.kt | 0 .../samplekotlin/presentation/BookViewModel.kt | 0 .../samplekotlin/presentation/MainActivity.kt | 0 .../app/src/main/res/drawable/badge_bg.xml | 0 .../app/src/main/res/drawable/ic_kotlin_logo.xml | 0 .../main/res/drawable/ic_launcher_background.xml | 0 .../main/res/drawable/ic_launcher_foreground.xml | 0 .../app/src/main/res/drawable/search_bg.xml | 0 .../app/src/main/res/layout/activity_main.xml | 0 .../app/src/main/res/layout/item_book.xml | 0 .../src/main/res/mipmap-anydpi-v26/ic_launcher.xml | 0 .../res/mipmap-anydpi-v26/ic_launcher_round.xml | 0 .../app/src/main/res/mipmap-hdpi/ic_launcher.webp | Bin .../src/main/res/mipmap-hdpi/ic_launcher_round.webp | Bin .../app/src/main/res/mipmap-mdpi/ic_launcher.webp | Bin .../src/main/res/mipmap-mdpi/ic_launcher_round.webp | Bin .../app/src/main/res/mipmap-xhdpi/ic_launcher.webp | Bin .../main/res/mipmap-xhdpi/ic_launcher_round.webp | Bin .../app/src/main/res/mipmap-xxhdpi/ic_launcher.webp | Bin .../main/res/mipmap-xxhdpi/ic_launcher_round.webp | Bin .../src/main/res/mipmap-xxxhdpi/ic_launcher.webp | Bin .../main/res/mipmap-xxxhdpi/ic_launcher_round.webp | Bin .../app/src/main/res/values-night/themes.xml | 0 .../app/src/main/res/values/colors.xml | 0 .../app/src/main/res/values/strings.xml | 0 .../app/src/main/res/values/themes.xml | 0 .../app/src/main/res/xml/backup_rules.xml | 0 .../app/src/main/res/xml/data_extraction_rules.xml | 0 .../org/typesense/samplekotlin/ExampleUnitTest.kt | 0 .../build.gradle.kts | 0 .../gradle.properties | 0 .../gradle/libs.versions.toml | 0 .../gradle/wrapper/gradle-wrapper.jar | Bin .../gradle/wrapper/gradle-wrapper.properties | 0 .../gradlew | 0 .../gradlew.bat | 0 .../settings.gradle.kts | 0 48 files changed, 2 insertions(+) rename {typesense-kotlin => typesense-kotlin-search}/.gitignore (100%) rename {typesense-kotlin => typesense-kotlin-search}/app/.gitignore (100%) rename {typesense-kotlin => typesense-kotlin-search}/app/build.gradle.kts (100%) rename {typesense-kotlin => typesense-kotlin-search}/app/proguard-rules.pro (100%) rename {typesense-kotlin => typesense-kotlin-search}/app/src/androidTest/java/org/typesense/samplekotlin/ExampleInstrumentedTest.kt (100%) rename {typesense-kotlin => typesense-kotlin-search}/app/src/main/AndroidManifest.xml (100%) rename {typesense-kotlin => typesense-kotlin-search}/app/src/main/java/org/typesense/samplekotlin/data/repository/TypesenseBookRepository.kt (100%) rename {typesense-kotlin => typesense-kotlin-search}/app/src/main/java/org/typesense/samplekotlin/domain/model/Book.kt (100%) rename {typesense-kotlin => typesense-kotlin-search}/app/src/main/java/org/typesense/samplekotlin/domain/repository/BookRepository.kt (100%) rename {typesense-kotlin => typesense-kotlin-search}/app/src/main/java/org/typesense/samplekotlin/domain/usecase/SearchBooksUseCase.kt (100%) rename {typesense-kotlin => typesense-kotlin-search}/app/src/main/java/org/typesense/samplekotlin/presentation/BookAdapter.kt (100%) rename {typesense-kotlin => typesense-kotlin-search}/app/src/main/java/org/typesense/samplekotlin/presentation/BookViewModel.kt (100%) rename {typesense-kotlin => typesense-kotlin-search}/app/src/main/java/org/typesense/samplekotlin/presentation/MainActivity.kt (100%) rename {typesense-kotlin => typesense-kotlin-search}/app/src/main/res/drawable/badge_bg.xml (100%) rename {typesense-kotlin => typesense-kotlin-search}/app/src/main/res/drawable/ic_kotlin_logo.xml (100%) rename {typesense-kotlin => typesense-kotlin-search}/app/src/main/res/drawable/ic_launcher_background.xml (100%) rename {typesense-kotlin => typesense-kotlin-search}/app/src/main/res/drawable/ic_launcher_foreground.xml (100%) rename {typesense-kotlin => typesense-kotlin-search}/app/src/main/res/drawable/search_bg.xml (100%) rename {typesense-kotlin => typesense-kotlin-search}/app/src/main/res/layout/activity_main.xml (100%) rename {typesense-kotlin => typesense-kotlin-search}/app/src/main/res/layout/item_book.xml (100%) rename {typesense-kotlin => typesense-kotlin-search}/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml (100%) rename {typesense-kotlin => typesense-kotlin-search}/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml (100%) rename {typesense-kotlin => typesense-kotlin-search}/app/src/main/res/mipmap-hdpi/ic_launcher.webp (100%) rename {typesense-kotlin => typesense-kotlin-search}/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp (100%) rename {typesense-kotlin => typesense-kotlin-search}/app/src/main/res/mipmap-mdpi/ic_launcher.webp (100%) rename {typesense-kotlin => typesense-kotlin-search}/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp (100%) rename {typesense-kotlin => typesense-kotlin-search}/app/src/main/res/mipmap-xhdpi/ic_launcher.webp (100%) rename {typesense-kotlin => typesense-kotlin-search}/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp (100%) rename {typesense-kotlin => typesense-kotlin-search}/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp (100%) rename {typesense-kotlin => typesense-kotlin-search}/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp (100%) rename {typesense-kotlin => typesense-kotlin-search}/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp (100%) rename {typesense-kotlin => typesense-kotlin-search}/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp (100%) rename {typesense-kotlin => typesense-kotlin-search}/app/src/main/res/values-night/themes.xml (100%) rename {typesense-kotlin => typesense-kotlin-search}/app/src/main/res/values/colors.xml (100%) rename {typesense-kotlin => typesense-kotlin-search}/app/src/main/res/values/strings.xml (100%) rename {typesense-kotlin => typesense-kotlin-search}/app/src/main/res/values/themes.xml (100%) rename {typesense-kotlin => typesense-kotlin-search}/app/src/main/res/xml/backup_rules.xml (100%) rename {typesense-kotlin => typesense-kotlin-search}/app/src/main/res/xml/data_extraction_rules.xml (100%) rename {typesense-kotlin => typesense-kotlin-search}/app/src/test/java/org/typesense/samplekotlin/ExampleUnitTest.kt (100%) rename {typesense-kotlin => typesense-kotlin-search}/build.gradle.kts (100%) rename {typesense-kotlin => typesense-kotlin-search}/gradle.properties (100%) rename {typesense-kotlin => typesense-kotlin-search}/gradle/libs.versions.toml (100%) rename {typesense-kotlin => typesense-kotlin-search}/gradle/wrapper/gradle-wrapper.jar (100%) rename {typesense-kotlin => typesense-kotlin-search}/gradle/wrapper/gradle-wrapper.properties (100%) rename {typesense-kotlin => typesense-kotlin-search}/gradlew (100%) rename {typesense-kotlin => typesense-kotlin-search}/gradlew.bat (100%) rename {typesense-kotlin => typesense-kotlin-search}/settings.gradle.kts (100%) diff --git a/README.md b/README.md index f6c0632..ee5e8ca 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,7 @@ code-samples/ ├── typesense-angular-search-bar/ # Angular + Typesense search implementation ├── typesense-astro-search/ # Astro + Typesense search implementation ├── typesense-gin-full-text-search/ # Go (Gin) + Typesense backend implementation +├── typesense-kotlin/ # Kotlin (Android) + Typesense search implementation ├── typesense-next-search-bar/ # Next.js + Typesense search implementation ├── typesense-nuxt-search-bar/ # Nuxt.js + Typesense search implementation ├── typesense-qwik-js-search/ # Qwik + Typesense search implementation @@ -31,6 +32,7 @@ code-samples/ | [typesense-angular-search-bar](./typesense-angular-search-bar) | Angular | A modern search bar with instant search capabilities | | [typesense-astro-search](./typesense-astro-search) | Astro | A modern search bar with instant search capabilities | | [typesense-gin-full-text-search](./typesense-gin-full-text-search) | Go (Gin) | Backend API with full-text search using Typesense | +| [typesense-kotlin](./typesense-kotlin) | Kotlin (Android) | A native Android search bar with instant search capabilities | | [typesense-next-search-bar](./typesense-next-search-bar) | Next.js | A modern search bar with instant search capabilities | | [typesense-nuxt-search-bar](./typesense-nuxt-search-bar) | Nuxt.js | A modern search bar with instant search capabilities | | [typesense-qwik-js-search](./typesense-qwik-js-search) | Qwik | Resumable search bar with real-time search and modern UI | diff --git a/typesense-kotlin/.gitignore b/typesense-kotlin-search/.gitignore similarity index 100% rename from typesense-kotlin/.gitignore rename to typesense-kotlin-search/.gitignore diff --git a/typesense-kotlin/app/.gitignore b/typesense-kotlin-search/app/.gitignore similarity index 100% rename from typesense-kotlin/app/.gitignore rename to typesense-kotlin-search/app/.gitignore diff --git a/typesense-kotlin/app/build.gradle.kts b/typesense-kotlin-search/app/build.gradle.kts similarity index 100% rename from typesense-kotlin/app/build.gradle.kts rename to typesense-kotlin-search/app/build.gradle.kts diff --git a/typesense-kotlin/app/proguard-rules.pro b/typesense-kotlin-search/app/proguard-rules.pro similarity index 100% rename from typesense-kotlin/app/proguard-rules.pro rename to typesense-kotlin-search/app/proguard-rules.pro diff --git a/typesense-kotlin/app/src/androidTest/java/org/typesense/samplekotlin/ExampleInstrumentedTest.kt b/typesense-kotlin-search/app/src/androidTest/java/org/typesense/samplekotlin/ExampleInstrumentedTest.kt similarity index 100% rename from typesense-kotlin/app/src/androidTest/java/org/typesense/samplekotlin/ExampleInstrumentedTest.kt rename to typesense-kotlin-search/app/src/androidTest/java/org/typesense/samplekotlin/ExampleInstrumentedTest.kt diff --git a/typesense-kotlin/app/src/main/AndroidManifest.xml b/typesense-kotlin-search/app/src/main/AndroidManifest.xml similarity index 100% rename from typesense-kotlin/app/src/main/AndroidManifest.xml rename to typesense-kotlin-search/app/src/main/AndroidManifest.xml diff --git a/typesense-kotlin/app/src/main/java/org/typesense/samplekotlin/data/repository/TypesenseBookRepository.kt b/typesense-kotlin-search/app/src/main/java/org/typesense/samplekotlin/data/repository/TypesenseBookRepository.kt similarity index 100% rename from typesense-kotlin/app/src/main/java/org/typesense/samplekotlin/data/repository/TypesenseBookRepository.kt rename to typesense-kotlin-search/app/src/main/java/org/typesense/samplekotlin/data/repository/TypesenseBookRepository.kt diff --git a/typesense-kotlin/app/src/main/java/org/typesense/samplekotlin/domain/model/Book.kt b/typesense-kotlin-search/app/src/main/java/org/typesense/samplekotlin/domain/model/Book.kt similarity index 100% rename from typesense-kotlin/app/src/main/java/org/typesense/samplekotlin/domain/model/Book.kt rename to typesense-kotlin-search/app/src/main/java/org/typesense/samplekotlin/domain/model/Book.kt diff --git a/typesense-kotlin/app/src/main/java/org/typesense/samplekotlin/domain/repository/BookRepository.kt b/typesense-kotlin-search/app/src/main/java/org/typesense/samplekotlin/domain/repository/BookRepository.kt similarity index 100% rename from typesense-kotlin/app/src/main/java/org/typesense/samplekotlin/domain/repository/BookRepository.kt rename to typesense-kotlin-search/app/src/main/java/org/typesense/samplekotlin/domain/repository/BookRepository.kt diff --git a/typesense-kotlin/app/src/main/java/org/typesense/samplekotlin/domain/usecase/SearchBooksUseCase.kt b/typesense-kotlin-search/app/src/main/java/org/typesense/samplekotlin/domain/usecase/SearchBooksUseCase.kt similarity index 100% rename from typesense-kotlin/app/src/main/java/org/typesense/samplekotlin/domain/usecase/SearchBooksUseCase.kt rename to typesense-kotlin-search/app/src/main/java/org/typesense/samplekotlin/domain/usecase/SearchBooksUseCase.kt diff --git a/typesense-kotlin/app/src/main/java/org/typesense/samplekotlin/presentation/BookAdapter.kt b/typesense-kotlin-search/app/src/main/java/org/typesense/samplekotlin/presentation/BookAdapter.kt similarity index 100% rename from typesense-kotlin/app/src/main/java/org/typesense/samplekotlin/presentation/BookAdapter.kt rename to typesense-kotlin-search/app/src/main/java/org/typesense/samplekotlin/presentation/BookAdapter.kt diff --git a/typesense-kotlin/app/src/main/java/org/typesense/samplekotlin/presentation/BookViewModel.kt b/typesense-kotlin-search/app/src/main/java/org/typesense/samplekotlin/presentation/BookViewModel.kt similarity index 100% rename from typesense-kotlin/app/src/main/java/org/typesense/samplekotlin/presentation/BookViewModel.kt rename to typesense-kotlin-search/app/src/main/java/org/typesense/samplekotlin/presentation/BookViewModel.kt diff --git a/typesense-kotlin/app/src/main/java/org/typesense/samplekotlin/presentation/MainActivity.kt b/typesense-kotlin-search/app/src/main/java/org/typesense/samplekotlin/presentation/MainActivity.kt similarity index 100% rename from typesense-kotlin/app/src/main/java/org/typesense/samplekotlin/presentation/MainActivity.kt rename to typesense-kotlin-search/app/src/main/java/org/typesense/samplekotlin/presentation/MainActivity.kt diff --git a/typesense-kotlin/app/src/main/res/drawable/badge_bg.xml b/typesense-kotlin-search/app/src/main/res/drawable/badge_bg.xml similarity index 100% rename from typesense-kotlin/app/src/main/res/drawable/badge_bg.xml rename to typesense-kotlin-search/app/src/main/res/drawable/badge_bg.xml diff --git a/typesense-kotlin/app/src/main/res/drawable/ic_kotlin_logo.xml b/typesense-kotlin-search/app/src/main/res/drawable/ic_kotlin_logo.xml similarity index 100% rename from typesense-kotlin/app/src/main/res/drawable/ic_kotlin_logo.xml rename to typesense-kotlin-search/app/src/main/res/drawable/ic_kotlin_logo.xml diff --git a/typesense-kotlin/app/src/main/res/drawable/ic_launcher_background.xml b/typesense-kotlin-search/app/src/main/res/drawable/ic_launcher_background.xml similarity index 100% rename from typesense-kotlin/app/src/main/res/drawable/ic_launcher_background.xml rename to typesense-kotlin-search/app/src/main/res/drawable/ic_launcher_background.xml diff --git a/typesense-kotlin/app/src/main/res/drawable/ic_launcher_foreground.xml b/typesense-kotlin-search/app/src/main/res/drawable/ic_launcher_foreground.xml similarity index 100% rename from typesense-kotlin/app/src/main/res/drawable/ic_launcher_foreground.xml rename to typesense-kotlin-search/app/src/main/res/drawable/ic_launcher_foreground.xml diff --git a/typesense-kotlin/app/src/main/res/drawable/search_bg.xml b/typesense-kotlin-search/app/src/main/res/drawable/search_bg.xml similarity index 100% rename from typesense-kotlin/app/src/main/res/drawable/search_bg.xml rename to typesense-kotlin-search/app/src/main/res/drawable/search_bg.xml diff --git a/typesense-kotlin/app/src/main/res/layout/activity_main.xml b/typesense-kotlin-search/app/src/main/res/layout/activity_main.xml similarity index 100% rename from typesense-kotlin/app/src/main/res/layout/activity_main.xml rename to typesense-kotlin-search/app/src/main/res/layout/activity_main.xml diff --git a/typesense-kotlin/app/src/main/res/layout/item_book.xml b/typesense-kotlin-search/app/src/main/res/layout/item_book.xml similarity index 100% rename from typesense-kotlin/app/src/main/res/layout/item_book.xml rename to typesense-kotlin-search/app/src/main/res/layout/item_book.xml diff --git a/typesense-kotlin/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/typesense-kotlin-search/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml similarity index 100% rename from typesense-kotlin/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml rename to typesense-kotlin-search/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml diff --git a/typesense-kotlin/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/typesense-kotlin-search/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml similarity index 100% rename from typesense-kotlin/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml rename to typesense-kotlin-search/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml diff --git a/typesense-kotlin/app/src/main/res/mipmap-hdpi/ic_launcher.webp b/typesense-kotlin-search/app/src/main/res/mipmap-hdpi/ic_launcher.webp similarity index 100% rename from typesense-kotlin/app/src/main/res/mipmap-hdpi/ic_launcher.webp rename to typesense-kotlin-search/app/src/main/res/mipmap-hdpi/ic_launcher.webp diff --git a/typesense-kotlin/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp b/typesense-kotlin-search/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp similarity index 100% rename from typesense-kotlin/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp rename to typesense-kotlin-search/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp diff --git a/typesense-kotlin/app/src/main/res/mipmap-mdpi/ic_launcher.webp b/typesense-kotlin-search/app/src/main/res/mipmap-mdpi/ic_launcher.webp similarity index 100% rename from typesense-kotlin/app/src/main/res/mipmap-mdpi/ic_launcher.webp rename to typesense-kotlin-search/app/src/main/res/mipmap-mdpi/ic_launcher.webp diff --git a/typesense-kotlin/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp b/typesense-kotlin-search/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp similarity index 100% rename from typesense-kotlin/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp rename to typesense-kotlin-search/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp diff --git a/typesense-kotlin/app/src/main/res/mipmap-xhdpi/ic_launcher.webp b/typesense-kotlin-search/app/src/main/res/mipmap-xhdpi/ic_launcher.webp similarity index 100% rename from typesense-kotlin/app/src/main/res/mipmap-xhdpi/ic_launcher.webp rename to typesense-kotlin-search/app/src/main/res/mipmap-xhdpi/ic_launcher.webp diff --git a/typesense-kotlin/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp b/typesense-kotlin-search/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp similarity index 100% rename from typesense-kotlin/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp rename to typesense-kotlin-search/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp diff --git a/typesense-kotlin/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp b/typesense-kotlin-search/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp similarity index 100% rename from typesense-kotlin/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp rename to typesense-kotlin-search/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp diff --git a/typesense-kotlin/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp b/typesense-kotlin-search/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp similarity index 100% rename from typesense-kotlin/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp rename to typesense-kotlin-search/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp diff --git a/typesense-kotlin/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp b/typesense-kotlin-search/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp similarity index 100% rename from typesense-kotlin/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp rename to typesense-kotlin-search/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp diff --git a/typesense-kotlin/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp b/typesense-kotlin-search/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp similarity index 100% rename from typesense-kotlin/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp rename to typesense-kotlin-search/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp diff --git a/typesense-kotlin/app/src/main/res/values-night/themes.xml b/typesense-kotlin-search/app/src/main/res/values-night/themes.xml similarity index 100% rename from typesense-kotlin/app/src/main/res/values-night/themes.xml rename to typesense-kotlin-search/app/src/main/res/values-night/themes.xml diff --git a/typesense-kotlin/app/src/main/res/values/colors.xml b/typesense-kotlin-search/app/src/main/res/values/colors.xml similarity index 100% rename from typesense-kotlin/app/src/main/res/values/colors.xml rename to typesense-kotlin-search/app/src/main/res/values/colors.xml diff --git a/typesense-kotlin/app/src/main/res/values/strings.xml b/typesense-kotlin-search/app/src/main/res/values/strings.xml similarity index 100% rename from typesense-kotlin/app/src/main/res/values/strings.xml rename to typesense-kotlin-search/app/src/main/res/values/strings.xml diff --git a/typesense-kotlin/app/src/main/res/values/themes.xml b/typesense-kotlin-search/app/src/main/res/values/themes.xml similarity index 100% rename from typesense-kotlin/app/src/main/res/values/themes.xml rename to typesense-kotlin-search/app/src/main/res/values/themes.xml diff --git a/typesense-kotlin/app/src/main/res/xml/backup_rules.xml b/typesense-kotlin-search/app/src/main/res/xml/backup_rules.xml similarity index 100% rename from typesense-kotlin/app/src/main/res/xml/backup_rules.xml rename to typesense-kotlin-search/app/src/main/res/xml/backup_rules.xml diff --git a/typesense-kotlin/app/src/main/res/xml/data_extraction_rules.xml b/typesense-kotlin-search/app/src/main/res/xml/data_extraction_rules.xml similarity index 100% rename from typesense-kotlin/app/src/main/res/xml/data_extraction_rules.xml rename to typesense-kotlin-search/app/src/main/res/xml/data_extraction_rules.xml diff --git a/typesense-kotlin/app/src/test/java/org/typesense/samplekotlin/ExampleUnitTest.kt b/typesense-kotlin-search/app/src/test/java/org/typesense/samplekotlin/ExampleUnitTest.kt similarity index 100% rename from typesense-kotlin/app/src/test/java/org/typesense/samplekotlin/ExampleUnitTest.kt rename to typesense-kotlin-search/app/src/test/java/org/typesense/samplekotlin/ExampleUnitTest.kt diff --git a/typesense-kotlin/build.gradle.kts b/typesense-kotlin-search/build.gradle.kts similarity index 100% rename from typesense-kotlin/build.gradle.kts rename to typesense-kotlin-search/build.gradle.kts diff --git a/typesense-kotlin/gradle.properties b/typesense-kotlin-search/gradle.properties similarity index 100% rename from typesense-kotlin/gradle.properties rename to typesense-kotlin-search/gradle.properties diff --git a/typesense-kotlin/gradle/libs.versions.toml b/typesense-kotlin-search/gradle/libs.versions.toml similarity index 100% rename from typesense-kotlin/gradle/libs.versions.toml rename to typesense-kotlin-search/gradle/libs.versions.toml diff --git a/typesense-kotlin/gradle/wrapper/gradle-wrapper.jar b/typesense-kotlin-search/gradle/wrapper/gradle-wrapper.jar similarity index 100% rename from typesense-kotlin/gradle/wrapper/gradle-wrapper.jar rename to typesense-kotlin-search/gradle/wrapper/gradle-wrapper.jar diff --git a/typesense-kotlin/gradle/wrapper/gradle-wrapper.properties b/typesense-kotlin-search/gradle/wrapper/gradle-wrapper.properties similarity index 100% rename from typesense-kotlin/gradle/wrapper/gradle-wrapper.properties rename to typesense-kotlin-search/gradle/wrapper/gradle-wrapper.properties diff --git a/typesense-kotlin/gradlew b/typesense-kotlin-search/gradlew similarity index 100% rename from typesense-kotlin/gradlew rename to typesense-kotlin-search/gradlew diff --git a/typesense-kotlin/gradlew.bat b/typesense-kotlin-search/gradlew.bat similarity index 100% rename from typesense-kotlin/gradlew.bat rename to typesense-kotlin-search/gradlew.bat diff --git a/typesense-kotlin/settings.gradle.kts b/typesense-kotlin-search/settings.gradle.kts similarity index 100% rename from typesense-kotlin/settings.gradle.kts rename to typesense-kotlin-search/settings.gradle.kts From 86b9c141d6dcd32ad763f0e6bc884a3479c641bb Mon Sep 17 00:00:00 2001 From: Nikhiladiga Date: Wed, 20 May 2026 15:48:52 +0530 Subject: [PATCH 11/15] [FEAT]: initialize Typesense Swift search application with SwiftUI and ViewModel architecture --- README.md | 2 + typesense-swift-search/.gitignore | 45 +++ .../project.pbxproj | 337 ++++++++++++++++++ .../AccentColor.colorset/Contents.json | 11 + .../AppIcon.appiconset/Contents.json | 35 ++ .../Assets.xcassets/Contents.json | 6 + .../typesense-swift-search/BookCardView.swift | 39 ++ .../typesense-swift-search/ContentView.swift | 97 +++++ .../typesense-swift-search/Models.swift | 25 ++ .../SearchViewModel.swift | 62 ++++ .../TypesenseConfig.swift | 16 + .../typesense_swift_searchApp.swift | 10 + 12 files changed, 685 insertions(+) create mode 100644 typesense-swift-search/.gitignore create mode 100644 typesense-swift-search/typesense-swift-search.xcodeproj/project.pbxproj create mode 100644 typesense-swift-search/typesense-swift-search/Assets.xcassets/AccentColor.colorset/Contents.json create mode 100644 typesense-swift-search/typesense-swift-search/Assets.xcassets/AppIcon.appiconset/Contents.json create mode 100644 typesense-swift-search/typesense-swift-search/Assets.xcassets/Contents.json create mode 100644 typesense-swift-search/typesense-swift-search/BookCardView.swift create mode 100644 typesense-swift-search/typesense-swift-search/ContentView.swift create mode 100644 typesense-swift-search/typesense-swift-search/Models.swift create mode 100644 typesense-swift-search/typesense-swift-search/SearchViewModel.swift create mode 100644 typesense-swift-search/typesense-swift-search/TypesenseConfig.swift create mode 100644 typesense-swift-search/typesense-swift-search/typesense_swift_searchApp.swift diff --git a/README.md b/README.md index ee5e8ca..7b39b60 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ code-samples/ ├── typesense-node-prisma-full-text-search/ # Node.js (Express) + Typesense + Prisma backend implementation ├── typesense-node-sequelize-full-text-search/ # Node.js (Express) + Typesense + Sequelize backend implementation ├── typesense-node-drizzle-full-text-search/ # Node.js (Express) + Typesense + Drizzle backend implementation +├── typesense-swift-search/ # Swift (iOS) + Typesense search implementation ├── typesense-vanilla-js-search/ # Vanilla JS + Typesense search implementation └── README.md # You are here ``` @@ -42,6 +43,7 @@ code-samples/ | [typesense-node-prisma-full-text-search](./typesense-node-prisma-full-text-search) | Node.js (Express) + Typesense + Prisma | Backend API with full-text search using Typesense | | [typesense-node-sequelize-full-text-search](./typesense-node-sequelize-full-text-search) | Node.js (Express) + Typesense + Sequelize | Backend API with full-text search using Typesense | | [typesense-node-drizzle-search-app](./typesense-node-drizzle-search-app) | Node.js (Express) + Typesense + Drizzle | Backend API with full-text search using Typesense | +| [typesense-swift-search](./typesense-swift-search) | Swift (iOS) | A native iOS search app with instant search capabilities | | [typesense-vanilla-js-search](./typesense-vanilla-js-search) | Vanilla JS | A modern search bar with instant search capabilities | ## Getting Started diff --git a/typesense-swift-search/.gitignore b/typesense-swift-search/.gitignore new file mode 100644 index 0000000..7c4bb42 --- /dev/null +++ b/typesense-swift-search/.gitignore @@ -0,0 +1,45 @@ +# Xcode +# +# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore + +## User settings +xcuserdata/ + +## compatibility with Xcode 8 and earlier (ignoring not only xcworkspace but also xcworkspace/xcuserdata) +*.xcworkspace/ + +## Xcode 8 and earlier +*.xcuserstate + +## build state +build/ +DerivedData/ + +## Other +*.hmap +*.ipa +*.dSYM.zip +*.dSYM + +# Swift Package Manager +# +# Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. +# Packages/ +# Package.resolved +# .build/ + +# CocoaPods +# +# We recommend against adding the Pods directory to your .gitignore. However +# you should judge for yourself, the pros and cons are mentioned at: +# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control +# +# Pods/ + +# Carthage +# +# Add this line if you want to avoid checking in build files from Carthage dependencies. +# Carthage/Build + +# Mac OS X +.DS_Store diff --git a/typesense-swift-search/typesense-swift-search.xcodeproj/project.pbxproj b/typesense-swift-search/typesense-swift-search.xcodeproj/project.pbxproj new file mode 100644 index 0000000..c59a3dd --- /dev/null +++ b/typesense-swift-search/typesense-swift-search.xcodeproj/project.pbxproj @@ -0,0 +1,337 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 77; + objects = { + +/* Begin PBXFileReference section */ + 84B32B942FBB0FE600CCFCF8 /* typesense-swift-search.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "typesense-swift-search.app"; sourceTree = BUILT_PRODUCTS_DIR; }; +/* End PBXFileReference section */ + +/* Begin PBXFileSystemSynchronizedRootGroup section */ + 84B32B962FBB0FE600CCFCF8 /* typesense-swift-search */ = { + isa = PBXFileSystemSynchronizedRootGroup; + path = "typesense-swift-search"; + sourceTree = ""; + }; +/* End PBXFileSystemSynchronizedRootGroup section */ + +/* Begin PBXFrameworksBuildPhase section */ + 84B32B912FBB0FE600CCFCF8 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 84B32B8B2FBB0FE600CCFCF8 = { + isa = PBXGroup; + children = ( + 84B32B962FBB0FE600CCFCF8 /* typesense-swift-search */, + 84B32B952FBB0FE600CCFCF8 /* Products */, + ); + sourceTree = ""; + }; + 84B32B952FBB0FE600CCFCF8 /* Products */ = { + isa = PBXGroup; + children = ( + 84B32B942FBB0FE600CCFCF8 /* typesense-swift-search.app */, + ); + name = Products; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 84B32B932FBB0FE600CCFCF8 /* typesense-swift-search */ = { + isa = PBXNativeTarget; + buildConfigurationList = 84B32B9F2FBB0FEA00CCFCF8 /* Build configuration list for PBXNativeTarget "typesense-swift-search" */; + buildPhases = ( + 84B32B902FBB0FE600CCFCF8 /* Sources */, + 84B32B912FBB0FE600CCFCF8 /* Frameworks */, + 84B32B922FBB0FE600CCFCF8 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + fileSystemSynchronizedGroups = ( + 84B32B962FBB0FE600CCFCF8 /* typesense-swift-search */, + ); + name = "typesense-swift-search"; + packageProductDependencies = ( + ); + productName = "typesense-swift-search"; + productReference = 84B32B942FBB0FE600CCFCF8 /* typesense-swift-search.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 84B32B8C2FBB0FE600CCFCF8 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = 1; + LastSwiftUpdateCheck = 2650; + LastUpgradeCheck = 2650; + TargetAttributes = { + 84B32B932FBB0FE600CCFCF8 = { + CreatedOnToolsVersion = 26.5; + }; + }; + }; + buildConfigurationList = 84B32B8F2FBB0FE600CCFCF8 /* Build configuration list for PBXProject "typesense-swift-search" */; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 84B32B8B2FBB0FE600CCFCF8; + minimizedProjectReferenceProxies = 1; + preferredProjectObjectVersion = 77; + productRefGroup = 84B32B952FBB0FE600CCFCF8 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 84B32B932FBB0FE600CCFCF8 /* typesense-swift-search */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 84B32B922FBB0FE600CCFCF8 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 84B32B902FBB0FE600CCFCF8 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin XCBuildConfiguration section */ + 84B32B9D2FBB0FEA00CCFCF8 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + DEVELOPMENT_TEAM = KXP93KQZ34; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 26.5; + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 84B32B9E2FBB0FEA00CCFCF8 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEVELOPMENT_TEAM = KXP93KQZ34; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 26.5; + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + SDKROOT = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 84B32BA02FBB0FEA00CCFCF8 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = KXP93KQZ34; + ENABLE_PREVIEWS = YES; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES; + INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES; + INFOPLIST_KEY_UILaunchScreen_Generation = YES; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = "org.typesense.typesense-swift-search"; + PRODUCT_NAME = "$(TARGET_NAME)"; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SWIFT_APPROACHABLE_CONCURRENCY = YES; + SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 84B32BA12FBB0FEA00CCFCF8 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = KXP93KQZ34; + ENABLE_PREVIEWS = YES; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES; + INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES; + INFOPLIST_KEY_UILaunchScreen_Generation = YES; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = "org.typesense.typesense-swift-search"; + PRODUCT_NAME = "$(TARGET_NAME)"; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SWIFT_APPROACHABLE_CONCURRENCY = YES; + SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 84B32B8F2FBB0FE600CCFCF8 /* Build configuration list for PBXProject "typesense-swift-search" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 84B32B9D2FBB0FEA00CCFCF8 /* Debug */, + 84B32B9E2FBB0FEA00CCFCF8 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 84B32B9F2FBB0FEA00CCFCF8 /* Build configuration list for PBXNativeTarget "typesense-swift-search" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 84B32BA02FBB0FEA00CCFCF8 /* Debug */, + 84B32BA12FBB0FEA00CCFCF8 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 84B32B8C2FBB0FE600CCFCF8 /* Project object */; +} diff --git a/typesense-swift-search/typesense-swift-search/Assets.xcassets/AccentColor.colorset/Contents.json b/typesense-swift-search/typesense-swift-search/Assets.xcassets/AccentColor.colorset/Contents.json new file mode 100644 index 0000000..eb87897 --- /dev/null +++ b/typesense-swift-search/typesense-swift-search/Assets.xcassets/AccentColor.colorset/Contents.json @@ -0,0 +1,11 @@ +{ + "colors" : [ + { + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/typesense-swift-search/typesense-swift-search/Assets.xcassets/AppIcon.appiconset/Contents.json b/typesense-swift-search/typesense-swift-search/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..2305880 --- /dev/null +++ b/typesense-swift-search/typesense-swift-search/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,35 @@ +{ + "images" : [ + { + "idiom" : "universal", + "platform" : "ios", + "size" : "1024x1024" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + } + ], + "idiom" : "universal", + "platform" : "ios", + "size" : "1024x1024" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "tinted" + } + ], + "idiom" : "universal", + "platform" : "ios", + "size" : "1024x1024" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/typesense-swift-search/typesense-swift-search/Assets.xcassets/Contents.json b/typesense-swift-search/typesense-swift-search/Assets.xcassets/Contents.json new file mode 100644 index 0000000..73c0059 --- /dev/null +++ b/typesense-swift-search/typesense-swift-search/Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/typesense-swift-search/typesense-swift-search/BookCardView.swift b/typesense-swift-search/typesense-swift-search/BookCardView.swift new file mode 100644 index 0000000..1fcd14d --- /dev/null +++ b/typesense-swift-search/typesense-swift-search/BookCardView.swift @@ -0,0 +1,39 @@ +import SwiftUI + +struct BookCardView: View { + let book: Book + + var body: some View { + VStack(alignment: .leading, spacing: 8) { + AsyncImage(url: URL(string: book.imageUrl)) { image in + image + .resizable() + .aspectRatio(contentMode: .fill) + } placeholder: { + Color.gray + } + .frame(height: 200) + .clipped() + .cornerRadius(12) + + VStack(alignment: .leading, spacing: 4) { + Text(book.title) + .font(.system(size: 16, weight: .bold)) + .foregroundColor(.white) + .lineLimit(2) + + Text(book.authors.joined(separator: ", ")) + .font(.system(size: 14)) + .foregroundColor(Color(red: 204/255, green: 204/255, blue: 204/255)) + .lineLimit(1) + + Text("\(String(book.publicationYear))") + .font(.system(size: 12)) + .foregroundColor(Color(red: 153/255, green: 153/255, blue: 153/255)) + } + .padding([.horizontal, .bottom], 12) + } + .background(Color(red: 51/255, green: 51/255, blue: 51/255)) + .cornerRadius(12) + } +} diff --git a/typesense-swift-search/typesense-swift-search/ContentView.swift b/typesense-swift-search/typesense-swift-search/ContentView.swift new file mode 100644 index 0000000..7c63922 --- /dev/null +++ b/typesense-swift-search/typesense-swift-search/ContentView.swift @@ -0,0 +1,97 @@ +import SwiftUI + +struct ContentView: View { + @StateObject private var viewModel = SearchViewModel() + + private let columns = [ + GridItem(.flexible(), spacing: 16), + GridItem(.flexible(), spacing: 16) + ] + + var body: some View { + ZStack { + Color(red: 34/255, green: 34/255, blue: 34/255) + .ignoresSafeArea() + + VStack(spacing: 0) { + // Header + VStack(spacing: 16) { + Text("Book Search") + .font(.system(size: 40, weight: .bold)) + .foregroundColor(.white) + + HStack(spacing: 6) { + Text("powered by") + .foregroundColor(Color(white: 0.7)) + .font(.system(size: 14)) + Text("typesense") + .foregroundColor(Color(red: 236/255, green: 72/255, blue: 127/255)) + .font(.system(size: 14, weight: .semibold)) + Text("&") + .foregroundColor(Color(white: 0.7)) + .font(.system(size: 14)) + Image(systemName: "swift") + .foregroundColor(.orange) + .font(.system(size: 16)) + } + .padding(.horizontal, 16) + .padding(.vertical, 8) + .background(Color(red: 45/255, green: 45/255, blue: 45/255)) + .cornerRadius(20) + .overlay( + RoundedRectangle(cornerRadius: 20) + .stroke(Color.white.opacity(0.1), lineWidth: 1) + ) + } + .padding(.top, 40) + .padding(.bottom, 20) + + // Search Bar + HStack { + Image(systemName: "magnifyingglass") + .foregroundColor(.gray) + + TextField("Search books...", text: $viewModel.searchText) + .foregroundColor(.white) + .accentColor(.white) + } + .padding(15) + .background(Color(red: 68/255, green: 68/255, blue: 68/255)) + .cornerRadius(10) + .padding(.horizontal, 20) + .padding(.top, 10) + .padding(.bottom, 20) + + if viewModel.isSearching && viewModel.results.isEmpty { + ProgressView() + .progressViewStyle(CircularProgressViewStyle(tint: .white)) + .padding() + Spacer() + } else if viewModel.results.isEmpty && !viewModel.searchText.isEmpty { + Text("No results found") + .foregroundColor(.gray) + .padding() + Spacer() + } else { + ScrollView { + LazyVGrid(columns: columns, spacing: 16) { + ForEach(viewModel.results) { book in + BookCardView(book: book) + } + } + .padding(.horizontal, 16) + } + } + } + } + .onAppear { + if viewModel.results.isEmpty && viewModel.searchText.isEmpty { + viewModel.triggerSearch() + } + } + } +} + +#Preview { + ContentView() +} diff --git a/typesense-swift-search/typesense-swift-search/Models.swift b/typesense-swift-search/typesense-swift-search/Models.swift new file mode 100644 index 0000000..ce0f9a0 --- /dev/null +++ b/typesense-swift-search/typesense-swift-search/Models.swift @@ -0,0 +1,25 @@ +import Foundation + +struct Book: Identifiable, Codable { + let id: String + let title: String + let authors: [String] + let publicationYear: Int + let imageUrl: String + + enum CodingKeys: String, CodingKey { + case id + case title + case authors + case publicationYear = "publication_year" + case imageUrl = "image_url" + } +} + +struct TypesenseSearchResult: Codable { + let hits: [TypesenseHit] +} + +struct TypesenseHit: Codable { + let document: Book +} diff --git a/typesense-swift-search/typesense-swift-search/SearchViewModel.swift b/typesense-swift-search/typesense-swift-search/SearchViewModel.swift new file mode 100644 index 0000000..76fb25b --- /dev/null +++ b/typesense-swift-search/typesense-swift-search/SearchViewModel.swift @@ -0,0 +1,62 @@ +import Foundation +import Combine + +@MainActor +class SearchViewModel: ObservableObject { + @Published var searchText = "" + @Published var results: [Book] = [] + @Published var isSearching = false + + private var searchTask: Task? + private var cancellables = Set() + + init() { + $searchText + .debounce(for: .milliseconds(300), scheduler: RunLoop.main) + .removeDuplicates() + .sink { [weak self] _ in + self?.triggerSearch() + } + .store(in: &cancellables) + } + + func triggerSearch() { + searchTask?.cancel() + + let query = searchText.isEmpty ? "*" : searchText + + self.isSearching = true + + searchTask = Task { + do { + let books = try await self.performSearch(query: query) + if !Task.isCancelled { + self.results = books + self.isSearching = false + } + } catch { + if !Task.isCancelled { + print("Search error: \(error)") + self.results = [] + self.isSearching = false + } + } + } + } + + private func performSearch(query: String) async throws -> [Book] { + var urlComponents = URLComponents(url: TypesenseConfig.baseURL.appendingPathComponent("collections/\(TypesenseConfig.collection)/documents/search"), resolvingAgainstBaseURL: false)! + + urlComponents.queryItems = [ + URLQueryItem(name: "q", value: query), + URLQueryItem(name: "query_by", value: "title,authors") + ] + + var request = URLRequest(url: urlComponents.url!) + request.addValue(TypesenseConfig.apiKey, forHTTPHeaderField: "X-TYPESENSE-API-KEY") + + let (data, _) = try await URLSession.shared.data(for: request) + let response = try JSONDecoder().decode(TypesenseSearchResult.self, from: data) + return response.hits.map { $0.document } + } +} diff --git a/typesense-swift-search/typesense-swift-search/TypesenseConfig.swift b/typesense-swift-search/typesense-swift-search/TypesenseConfig.swift new file mode 100644 index 0000000..daf00e6 --- /dev/null +++ b/typesense-swift-search/typesense-swift-search/TypesenseConfig.swift @@ -0,0 +1,16 @@ +import Foundation + +struct TypesenseConfig { + // For Production, use your Typesense Cloud host and port 443 with https + static let host = "localhost" + static let port = "8108" + static let scheme = "http" + + // IMPORTANT: In a production iOS app, ALWAYS use a Search-Only API Key, never an Admin Key. + static let apiKey = "xyz" + static let collection = "books" + + static var baseURL: URL { + URL(string: "\(scheme)://\(host):\(port)")! + } +} diff --git a/typesense-swift-search/typesense-swift-search/typesense_swift_searchApp.swift b/typesense-swift-search/typesense-swift-search/typesense_swift_searchApp.swift new file mode 100644 index 0000000..94e9705 --- /dev/null +++ b/typesense-swift-search/typesense-swift-search/typesense_swift_searchApp.swift @@ -0,0 +1,10 @@ +import SwiftUI + +@main +struct typesense_swift_searchApp: App { + var body: some Scene { + WindowGroup { + ContentView() + } + } +} From b410ea6d0da051f28c3dfcf6b3c6a0cb804d6b61 Mon Sep 17 00:00:00 2001 From: Nikhiladiga Date: Wed, 20 May 2026 22:13:46 +0530 Subject: [PATCH 12/15] First revision: migrate networking to official Typesense Swift SDK --- .../project.pbxproj | 23 ++++++++++++++++++ .../typesense-swift-search/Models.swift | 8 ------- .../SearchViewModel.swift | 24 +++++++++---------- 3 files changed, 35 insertions(+), 20 deletions(-) diff --git a/typesense-swift-search/typesense-swift-search.xcodeproj/project.pbxproj b/typesense-swift-search/typesense-swift-search.xcodeproj/project.pbxproj index c59a3dd..a2f3368 100644 --- a/typesense-swift-search/typesense-swift-search.xcodeproj/project.pbxproj +++ b/typesense-swift-search/typesense-swift-search.xcodeproj/project.pbxproj @@ -65,6 +65,7 @@ ); name = "typesense-swift-search"; packageProductDependencies = ( + 84B32BB02FBB0FEB00CCFCF8 /* Typesense */, ); productName = "typesense-swift-search"; productReference = 84B32B942FBB0FE600CCFCF8 /* typesense-swift-search.app */; @@ -101,6 +102,9 @@ targets = ( 84B32B932FBB0FE600CCFCF8 /* typesense-swift-search */, ); + packageReferences = ( + 84B32BAF2FBB0FEB00CCFCF8 /* XCRemoteSwiftPackageReference "typesense-swift" */, + ); }; /* End PBXProject section */ @@ -124,6 +128,25 @@ }; /* End PBXSourcesBuildPhase section */ +/* Begin XCRemoteSwiftPackageReference section */ + 84B32BAF2FBB0FEB00CCFCF8 /* XCRemoteSwiftPackageReference "typesense-swift" */ = { + isa = XCRemoteSwiftPackageReference; + repositoryURL = "https://github.com/typesense/typesense-swift"; + requirement = { + kind = upToNextMajorVersion; + minimumVersion = 1.0.0; + }; + }; +/* End XCRemoteSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 84B32BB02FBB0FEB00CCFCF8 /* Typesense */ = { + isa = XCSwiftPackageProductDependency; + package = 84B32BAF2FBB0FEB00CCFCF8 /* XCRemoteSwiftPackageReference "typesense-swift" */; + productName = Typesense; + }; +/* End XCSwiftPackageProductDependency section */ + /* Begin XCBuildConfiguration section */ 84B32B9D2FBB0FEA00CCFCF8 /* Debug */ = { isa = XCBuildConfiguration; diff --git a/typesense-swift-search/typesense-swift-search/Models.swift b/typesense-swift-search/typesense-swift-search/Models.swift index ce0f9a0..6e275ca 100644 --- a/typesense-swift-search/typesense-swift-search/Models.swift +++ b/typesense-swift-search/typesense-swift-search/Models.swift @@ -15,11 +15,3 @@ struct Book: Identifiable, Codable { case imageUrl = "image_url" } } - -struct TypesenseSearchResult: Codable { - let hits: [TypesenseHit] -} - -struct TypesenseHit: Codable { - let document: Book -} diff --git a/typesense-swift-search/typesense-swift-search/SearchViewModel.swift b/typesense-swift-search/typesense-swift-search/SearchViewModel.swift index 76fb25b..a84c9a7 100644 --- a/typesense-swift-search/typesense-swift-search/SearchViewModel.swift +++ b/typesense-swift-search/typesense-swift-search/SearchViewModel.swift @@ -1,5 +1,6 @@ import Foundation import Combine +import Typesense @MainActor class SearchViewModel: ObservableObject { @@ -7,10 +8,15 @@ class SearchViewModel: ObservableObject { @Published var results: [Book] = [] @Published var isSearching = false + private let client: Client private var searchTask: Task? private var cancellables = Set() init() { + let node = Node(host: TypesenseConfig.host, port: TypesenseConfig.port, nodeProtocol: TypesenseConfig.scheme) + let config = Configuration(nodes: [node], apiKey: TypesenseConfig.apiKey) + self.client = Client(config: config) + $searchText .debounce(for: .milliseconds(300), scheduler: RunLoop.main) .removeDuplicates() @@ -45,18 +51,12 @@ class SearchViewModel: ObservableObject { } private func performSearch(query: String) async throws -> [Book] { - var urlComponents = URLComponents(url: TypesenseConfig.baseURL.appendingPathComponent("collections/\(TypesenseConfig.collection)/documents/search"), resolvingAgainstBaseURL: false)! - - urlComponents.queryItems = [ - URLQueryItem(name: "q", value: query), - URLQueryItem(name: "query_by", value: "title,authors") - ] - - var request = URLRequest(url: urlComponents.url!) - request.addValue(TypesenseConfig.apiKey, forHTTPHeaderField: "X-TYPESENSE-API-KEY") + let searchParameters = SearchParameters(q: query, queryBy: "title,authors") + let (searchResult, _) = try await client + .collection(name: TypesenseConfig.collection) + .documents() + .search(searchParameters, for: Book.self) - let (data, _) = try await URLSession.shared.data(for: request) - let response = try JSONDecoder().decode(TypesenseSearchResult.self, from: data) - return response.hits.map { $0.document } + return searchResult?.hits?.compactMap { $0.document } ?? [] } } From 1030b220dafc57b5831e19d0f7170b5a73939390 Mon Sep 17 00:00:00 2001 From: Nikhiladiga Date: Sun, 24 May 2026 22:44:04 +0530 Subject: [PATCH 13/15] [FEATURE]: add new SvelteKit search application using Typesense and instantsearch.js --- README.md | 2 + typesense-sveltekit-search-app/.gitignore | 23 +++ typesense-sveltekit-search-app/.npmrc | 1 + .../.prettierignore | 9 + typesense-sveltekit-search-app/.prettierrc | 16 ++ typesense-sveltekit-search-app/README.md | 77 ++++++++ typesense-sveltekit-search-app/package.json | 37 ++++ typesense-sveltekit-search-app/src/app.d.ts | 13 ++ typesense-sveltekit-search-app/src/app.html | 12 ++ .../src/lib/components/BookCard.svelte | 150 ++++++++++++++++ .../src/lib/components/BookList.svelte | 59 ++++++ .../src/lib/components/GithubIcon.svelte | 16 ++ .../src/lib/components/Heading.svelte | 135 ++++++++++++++ .../src/lib/components/SearchBar.svelte | 169 ++++++++++++++++++ .../src/lib/components/SvelteLogo.svelte | 15 ++ .../src/lib/instantSearchAdapter.ts | 26 +++ .../src/lib/searchService.svelte.ts | 69 +++++++ .../src/lib/types.ts | 10 ++ .../src/routes/+layout.svelte | 10 ++ .../src/routes/+page.svelte | 33 ++++ .../src/routes/+page.ts | 1 + .../src/routes/layout.css | 2 + .../static/favicon.png | Bin 0 -> 891 bytes .../static/robots.txt | 3 + .../svelte.config.js | 17 ++ typesense-sveltekit-search-app/tsconfig.json | 20 +++ typesense-sveltekit-search-app/vite.config.ts | 10 ++ 27 files changed, 935 insertions(+) create mode 100644 typesense-sveltekit-search-app/.gitignore create mode 100644 typesense-sveltekit-search-app/.npmrc create mode 100644 typesense-sveltekit-search-app/.prettierignore create mode 100644 typesense-sveltekit-search-app/.prettierrc create mode 100644 typesense-sveltekit-search-app/README.md create mode 100644 typesense-sveltekit-search-app/package.json create mode 100644 typesense-sveltekit-search-app/src/app.d.ts create mode 100644 typesense-sveltekit-search-app/src/app.html create mode 100644 typesense-sveltekit-search-app/src/lib/components/BookCard.svelte create mode 100644 typesense-sveltekit-search-app/src/lib/components/BookList.svelte create mode 100644 typesense-sveltekit-search-app/src/lib/components/GithubIcon.svelte create mode 100644 typesense-sveltekit-search-app/src/lib/components/Heading.svelte create mode 100644 typesense-sveltekit-search-app/src/lib/components/SearchBar.svelte create mode 100644 typesense-sveltekit-search-app/src/lib/components/SvelteLogo.svelte create mode 100644 typesense-sveltekit-search-app/src/lib/instantSearchAdapter.ts create mode 100644 typesense-sveltekit-search-app/src/lib/searchService.svelte.ts create mode 100644 typesense-sveltekit-search-app/src/lib/types.ts create mode 100644 typesense-sveltekit-search-app/src/routes/+layout.svelte create mode 100644 typesense-sveltekit-search-app/src/routes/+page.svelte create mode 100644 typesense-sveltekit-search-app/src/routes/+page.ts create mode 100644 typesense-sveltekit-search-app/src/routes/layout.css create mode 100644 typesense-sveltekit-search-app/static/favicon.png create mode 100644 typesense-sveltekit-search-app/static/robots.txt create mode 100644 typesense-sveltekit-search-app/svelte.config.js create mode 100644 typesense-sveltekit-search-app/tsconfig.json create mode 100644 typesense-sveltekit-search-app/vite.config.ts diff --git a/README.md b/README.md index 7b39b60..c521bd8 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ code-samples/ ├── typesense-node-prisma-full-text-search/ # Node.js (Express) + Typesense + Prisma backend implementation ├── typesense-node-sequelize-full-text-search/ # Node.js (Express) + Typesense + Sequelize backend implementation ├── typesense-node-drizzle-full-text-search/ # Node.js (Express) + Typesense + Drizzle backend implementation +├── typesense-sveltekit-search-app/ # SvelteKit + Typesense search implementation ├── typesense-swift-search/ # Swift (iOS) + Typesense search implementation ├── typesense-vanilla-js-search/ # Vanilla JS + Typesense search implementation └── README.md # You are here @@ -43,6 +44,7 @@ code-samples/ | [typesense-node-prisma-full-text-search](./typesense-node-prisma-full-text-search) | Node.js (Express) + Typesense + Prisma | Backend API with full-text search using Typesense | | [typesense-node-sequelize-full-text-search](./typesense-node-sequelize-full-text-search) | Node.js (Express) + Typesense + Sequelize | Backend API with full-text search using Typesense | | [typesense-node-drizzle-search-app](./typesense-node-drizzle-search-app) | Node.js (Express) + Typesense + Drizzle | Backend API with full-text search using Typesense | +| [typesense-sveltekit-search-app](./typesense-sveltekit-search-app) | SvelteKit | A modern search bar with instant search capabilities | | [typesense-swift-search](./typesense-swift-search) | Swift (iOS) | A native iOS search app with instant search capabilities | | [typesense-vanilla-js-search](./typesense-vanilla-js-search) | Vanilla JS | A modern search bar with instant search capabilities | diff --git a/typesense-sveltekit-search-app/.gitignore b/typesense-sveltekit-search-app/.gitignore new file mode 100644 index 0000000..3b462cb --- /dev/null +++ b/typesense-sveltekit-search-app/.gitignore @@ -0,0 +1,23 @@ +node_modules + +# Output +.output +.vercel +.netlify +.wrangler +/.svelte-kit +/build + +# OS +.DS_Store +Thumbs.db + +# Env +.env +.env.* +!.env.example +!.env.test + +# Vite +vite.config.js.timestamp-* +vite.config.ts.timestamp-* diff --git a/typesense-sveltekit-search-app/.npmrc b/typesense-sveltekit-search-app/.npmrc new file mode 100644 index 0000000..b6f27f1 --- /dev/null +++ b/typesense-sveltekit-search-app/.npmrc @@ -0,0 +1 @@ +engine-strict=true diff --git a/typesense-sveltekit-search-app/.prettierignore b/typesense-sveltekit-search-app/.prettierignore new file mode 100644 index 0000000..7d74fe2 --- /dev/null +++ b/typesense-sveltekit-search-app/.prettierignore @@ -0,0 +1,9 @@ +# Package Managers +package-lock.json +pnpm-lock.yaml +yarn.lock +bun.lock +bun.lockb + +# Miscellaneous +/static/ diff --git a/typesense-sveltekit-search-app/.prettierrc b/typesense-sveltekit-search-app/.prettierrc new file mode 100644 index 0000000..819fa57 --- /dev/null +++ b/typesense-sveltekit-search-app/.prettierrc @@ -0,0 +1,16 @@ +{ + "useTabs": true, + "singleQuote": true, + "trailingComma": "none", + "printWidth": 100, + "plugins": ["prettier-plugin-svelte", "prettier-plugin-tailwindcss"], + "overrides": [ + { + "files": "*.svelte", + "options": { + "parser": "svelte" + } + } + ], + "tailwindStylesheet": "./src/routes/layout.css" +} diff --git a/typesense-sveltekit-search-app/README.md b/typesense-sveltekit-search-app/README.md new file mode 100644 index 0000000..94ccefa --- /dev/null +++ b/typesense-sveltekit-search-app/README.md @@ -0,0 +1,77 @@ +# SvelteKit Search Bar with Typesense + +A modern search bar application built with SvelteKit and Typesense, featuring instant search capabilities. + +## Tech Stack + +- SvelteKit (Svelte 5) +- Typesense +- typesense-instantsearch-adapter & instantsearch.js + +## Prerequisites + +- Node.js 18+ and npm 9+. +- Docker (for running Typesense locally). Alternatively, you can use a Typesense Cloud cluster. +- Basic knowledge of Svelte and SvelteKit. + +## Quick Start + +### 1. Clone the repository + +```bash +git clone https://github.com/typesense/code-samples.git +cd typesense-sveltekit-search-app +``` + +### 2. Install dependencies + +```bash +npm install +``` + +### 3. Set up environment variables + +Create a `.env` file in the project root with the following content: + +```env +PUBLIC_TYPESENSE_API_KEY=xxx +PUBLIC_TYPESENSE_HOST=localhost +PUBLIC_TYPESENSE_PORT=8108 +PUBLIC_TYPESENSE_PROTOCOL=http +PUBLIC_TYPESENSE_INDEX=books +``` + +### 4. Project Structure + +```text +├── src +│ ├── lib +│ │ ├── components +│ │ │ └── UI components... +│ │ ├── instantSearchAdapter.ts +│ │ ├── searchService.svelte.ts +│ │ └── types.ts +│ └── routes +│ ├── +page.svelte +│ └── +page.ts +``` + +### 5. Start the development server + +```bash +npm run dev +``` + +Open [http://localhost:5173](http://localhost:5173) in your browser. + +### 6. Deployment + +Set env variables to point the app to the Typesense Cluster: + +```env +PUBLIC_TYPESENSE_API_KEY=xxx +PUBLIC_TYPESENSE_HOST=xxx.typesense.net +PUBLIC_TYPESENSE_PORT=443 +PUBLIC_TYPESENSE_PROTOCOL=https +PUBLIC_TYPESENSE_INDEX=books +``` diff --git a/typesense-sveltekit-search-app/package.json b/typesense-sveltekit-search-app/package.json new file mode 100644 index 0000000..df08b7d --- /dev/null +++ b/typesense-sveltekit-search-app/package.json @@ -0,0 +1,37 @@ +{ + "name": "typesense-sveltekit-search-app", + "private": true, + "version": "0.0.1", + "type": "module", + "scripts": { + "dev": "vite dev", + "build": "vite build", + "preview": "vite preview", + "prepare": "svelte-kit sync || echo ''", + "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json", + "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch", + "lint": "prettier --check .", + "format": "prettier --write ." + }, + "devDependencies": { + "@sveltejs/adapter-auto": "^7.0.1", + "@sveltejs/kit": "^2.57.0", + "@sveltejs/vite-plugin-svelte": "^7.0.0", + "@tailwindcss/typography": "^0.5.19", + "@tailwindcss/vite": "^4.2.2", + "@types/node": "^25.9.1", + "prettier": "^3.8.1", + "prettier-plugin-svelte": "^3.5.1", + "prettier-plugin-tailwindcss": "^0.7.2", + "svelte": "^5.55.2", + "svelte-check": "^4.4.6", + "tailwindcss": "^4.2.2", + "typescript": "^6.0.2", + "vite": "^8.0.7" + }, + "dependencies": { + "instantsearch.js": "^4.98.0", + "typesense": "^3.0.6", + "typesense-instantsearch-adapter": "^3.0.2" + } +} diff --git a/typesense-sveltekit-search-app/src/app.d.ts b/typesense-sveltekit-search-app/src/app.d.ts new file mode 100644 index 0000000..da08e6d --- /dev/null +++ b/typesense-sveltekit-search-app/src/app.d.ts @@ -0,0 +1,13 @@ +// See https://svelte.dev/docs/kit/types#app.d.ts +// for information about these interfaces +declare global { + namespace App { + // interface Error {} + // interface Locals {} + // interface PageData {} + // interface PageState {} + // interface Platform {} + } +} + +export {}; diff --git a/typesense-sveltekit-search-app/src/app.html b/typesense-sveltekit-search-app/src/app.html new file mode 100644 index 0000000..6a2bb58 --- /dev/null +++ b/typesense-sveltekit-search-app/src/app.html @@ -0,0 +1,12 @@ + + + + + + + %sveltekit.head% + + +

%sveltekit.body%
+ + diff --git a/typesense-sveltekit-search-app/src/lib/components/BookCard.svelte b/typesense-sveltekit-search-app/src/lib/components/BookCard.svelte new file mode 100644 index 0000000..b533fdd --- /dev/null +++ b/typesense-sveltekit-search-app/src/lib/components/BookCard.svelte @@ -0,0 +1,150 @@ + + +
+
+ {#if book.image_url && !imageError} + {book.title} imageError = true} + /> + {:else} +
+ + + + No Cover +
+ {/if} +
+
+

{book.title}

+

By: {book.authors?.join(", ") || 'Unknown Author'}

+ {#if book.publication_year} +

Published: {book.publication_year}

+ {/if} +
+
+ {"★".repeat(Math.round(book.average_rating || 0))} + {"☆".repeat(5 - Math.round(book.average_rating || 0))} +
+ + {book.average_rating?.toFixed(1) || '0.0'} + +
+
+
+ + diff --git a/typesense-sveltekit-search-app/src/lib/components/BookList.svelte b/typesense-sveltekit-search-app/src/lib/components/BookList.svelte new file mode 100644 index 0000000..c1994a2 --- /dev/null +++ b/typesense-sveltekit-search-app/src/lib/components/BookList.svelte @@ -0,0 +1,59 @@ + + +{#if !searchService.hasSearched} +
+ Loading search client... +
+{:else} + {#if searchService.hits.length === 0} +
+ {#if searchService.query} + No books found. Try a different search term. + {:else} + Start typing to search for books. + {/if} +
+ {:else} +
+ {#each searchService.hits as book (book.objectID || book.id)} + + {/each} +
+ {/if} +{/if} + + diff --git a/typesense-sveltekit-search-app/src/lib/components/GithubIcon.svelte b/typesense-sveltekit-search-app/src/lib/components/GithubIcon.svelte new file mode 100644 index 0000000..ae6f8e1 --- /dev/null +++ b/typesense-sveltekit-search-app/src/lib/components/GithubIcon.svelte @@ -0,0 +1,16 @@ + + + + + diff --git a/typesense-sveltekit-search-app/src/lib/components/Heading.svelte b/typesense-sveltekit-search-app/src/lib/components/Heading.svelte new file mode 100644 index 0000000..bfbb539 --- /dev/null +++ b/typesense-sveltekit-search-app/src/lib/components/Heading.svelte @@ -0,0 +1,135 @@ + + +
+

SvelteKit Search Bar

+
+ powered by{' '} + + typesense| + {' '} + & +
+
+ + + + + + diff --git a/typesense-sveltekit-search-app/src/lib/components/SearchBar.svelte b/typesense-sveltekit-search-app/src/lib/components/SearchBar.svelte new file mode 100644 index 0000000..3898d6f --- /dev/null +++ b/typesense-sveltekit-search-app/src/lib/components/SearchBar.svelte @@ -0,0 +1,169 @@ + + +
+
+ + + + + {#if inputValue} + + {/if} +
+
+ + diff --git a/typesense-sveltekit-search-app/src/lib/components/SvelteLogo.svelte b/typesense-sveltekit-search-app/src/lib/components/SvelteLogo.svelte new file mode 100644 index 0000000..f8edd5b --- /dev/null +++ b/typesense-sveltekit-search-app/src/lib/components/SvelteLogo.svelte @@ -0,0 +1,15 @@ + + + + svelte-logo + + + diff --git a/typesense-sveltekit-search-app/src/lib/instantSearchAdapter.ts b/typesense-sveltekit-search-app/src/lib/instantSearchAdapter.ts new file mode 100644 index 0000000..b37a7f9 --- /dev/null +++ b/typesense-sveltekit-search-app/src/lib/instantSearchAdapter.ts @@ -0,0 +1,26 @@ +import { + PUBLIC_TYPESENSE_API_KEY, + PUBLIC_TYPESENSE_HOST, + PUBLIC_TYPESENSE_PORT, + PUBLIC_TYPESENSE_PROTOCOL, +} from '$env/static/public'; +import TypesenseInstantsearchAdapter from 'typesense-instantsearch-adapter'; + +export const typesenseInstantSearchAdapter = new TypesenseInstantsearchAdapter({ + server: { + apiKey: PUBLIC_TYPESENSE_API_KEY || '1234', + nodes: [ + { + host: PUBLIC_TYPESENSE_HOST || 'localhost', + port: parseInt(PUBLIC_TYPESENSE_PORT || '8108'), + protocol: PUBLIC_TYPESENSE_PROTOCOL || 'http', + }, + ], + }, + additionalSearchParameters: { + query_by: 'title,authors', + query_by_weights: '4,2', + num_typos: 1, + sort_by: 'ratings_count:desc', + }, +}); diff --git a/typesense-sveltekit-search-app/src/lib/searchService.svelte.ts b/typesense-sveltekit-search-app/src/lib/searchService.svelte.ts new file mode 100644 index 0000000..017f175 --- /dev/null +++ b/typesense-sveltekit-search-app/src/lib/searchService.svelte.ts @@ -0,0 +1,69 @@ +import { PUBLIC_TYPESENSE_INDEX } from '$env/static/public'; +import { typesenseInstantSearchAdapter } from '$lib/instantSearchAdapter'; +import instantsearch from 'instantsearch.js'; +import connectHits from 'instantsearch.js/es/connectors/hits/connectHits'; +import connectSearchBox from 'instantsearch.js/es/connectors/search-box/connectSearchBox'; +import type { Book } from './types'; + +export class SearchService { + hits = $state([]); + query = $state(''); + loading = $state(false); + hasSearched = $state(false); + + private searchInstance: any; + private searchBoxWidget: any; + private hitsWidget: any; + private refineFn: (val: string) => void = () => {}; + + constructor() { + if (typeof window !== 'undefined') { + this.searchInstance = instantsearch({ + indexName: PUBLIC_TYPESENSE_INDEX || 'books', + searchClient: typesenseInstantSearchAdapter.searchClient, + future: { + preserveSharedStateOnUnmount: true, + }, + }); + } + } + + start() { + if (typeof window === 'undefined' || !this.searchInstance) return; + + const searchBoxConnector = connectSearchBox((renderOptions) => { + this.query = renderOptions.query; + this.refineFn = renderOptions.refine; + }); + + const hitsConnector = connectHits((renderOptions) => { + this.hits = renderOptions.hits as unknown as Book[]; + this.hasSearched = true; + }); + + this.searchBoxWidget = searchBoxConnector({}); + this.hitsWidget = hitsConnector({}); + + this.searchInstance.addWidgets([this.searchBoxWidget, this.hitsWidget]); + + this.searchInstance.on('render', () => { + const status = this.searchInstance.status; + const helperLoading = this.searchInstance.helper?.state?.loading; + this.loading = status === 'loading' || status === 'stalled' || !!helperLoading; + }); + + this.searchInstance.start(); + } + + refine(value: string) { + if (typeof window !== 'undefined' && this.refineFn) { + this.refineFn(value); + } + } + + destroy() { + if (typeof window !== 'undefined' && this.searchInstance) { + this.searchInstance.dispose(); + } + } +} diff --git a/typesense-sveltekit-search-app/src/lib/types.ts b/typesense-sveltekit-search-app/src/lib/types.ts new file mode 100644 index 0000000..21cc51c --- /dev/null +++ b/typesense-sveltekit-search-app/src/lib/types.ts @@ -0,0 +1,10 @@ +export type Book = { + id: string; + title: string; + authors: string[]; + publication_year: number; + average_rating: number; + image_url: string; + ratings_count: number; + objectID?: string; +}; diff --git a/typesense-sveltekit-search-app/src/routes/+layout.svelte b/typesense-sveltekit-search-app/src/routes/+layout.svelte new file mode 100644 index 0000000..07dd42e --- /dev/null +++ b/typesense-sveltekit-search-app/src/routes/+layout.svelte @@ -0,0 +1,10 @@ + + + + + +{@render children()} diff --git a/typesense-sveltekit-search-app/src/routes/+page.svelte b/typesense-sveltekit-search-app/src/routes/+page.svelte new file mode 100644 index 0000000..5a1e92d --- /dev/null +++ b/typesense-sveltekit-search-app/src/routes/+page.svelte @@ -0,0 +1,33 @@ + + + + SvelteKit Search Bar + + + +
+
+ + + +
+
diff --git a/typesense-sveltekit-search-app/src/routes/+page.ts b/typesense-sveltekit-search-app/src/routes/+page.ts new file mode 100644 index 0000000..a3d1578 --- /dev/null +++ b/typesense-sveltekit-search-app/src/routes/+page.ts @@ -0,0 +1 @@ +export const ssr = false; diff --git a/typesense-sveltekit-search-app/src/routes/layout.css b/typesense-sveltekit-search-app/src/routes/layout.css new file mode 100644 index 0000000..1c4d2a8 --- /dev/null +++ b/typesense-sveltekit-search-app/src/routes/layout.css @@ -0,0 +1,2 @@ +@import 'tailwindcss'; +@plugin '@tailwindcss/typography'; diff --git a/typesense-sveltekit-search-app/static/favicon.png b/typesense-sveltekit-search-app/static/favicon.png new file mode 100644 index 0000000000000000000000000000000000000000..f42ec1903d21e38742a5dc4d39b056fc66c078f6 GIT binary patch literal 891 zcmeAS@N?(olHy`uVBq!ia0vp^ML?Xx!3-oD?~5$~QY`^KA+A80iD3gX!v-dXjm!+| zfs7l>88?|SI2hJ5Fsz420R_Pb$OWp|2oYys*u(->03;b0wgOcOfVHqNY+wa3fXX)B zWXin7oDS5&#IXJbQ^qysOh$$cH<{C~vt$5mxxoaK0&+8C=iR*rbca?+kY6yv{r&X` z^Y_;)2=w1y|2`l;Ug5mG!~6#M_W}m}2LAEq-}@Kb4_Lq6VSfJit9q3{$JcneIEGZj zy}k81@3w+OL*jvDrrQkdj-T5YTmGl$|9A7$z}7=64qk3o58YG0_ywoRLB^D+c%Zf#`>FDkFKyh zBsA^PD<;l9xuaf9tC{sIo2iF(t@?C?wC%7h_ zkw1FSh+ng{MPbsLiEldA+8$JimY=j>(wB*AwyWR#rqc89q)<&SWV_?A>>34d_-6-5ungN=(OFNrj3u>+||fa+|g6fZE;N2Vx5*ZFqaqM#8e*MQ!1Uof=vDLrq^DyW5r4b|Y!x)Ku0? z``MD$CONzjtrB^);$Y>JgfF{h-Kl)TuVTGo)%)O3ukVucX8Xw43x=Pp3X;=Z^g(Q8 z#P<_l;#OYzZe+WD-8Fer&YdN1X8iVF-CdGv`Qp_2B8BV|ZhCVV!ms?-xi()VKIh4~ zol~y(cKw*37rbNIq+R*Ek-n4CX82qx*R*_kcmF-XmmzUR$1I+E7TLXJHN2&5_V?|_ z%^cObsr6n($8P-=)?eqh+rRRs8YG2Co|L~oUoSu3-@bn0{|ouMHvM;+xMS%BVCrS? MboFyt=akR{0FZr (filename.split(/[/\\]/).includes('node_modules') ? undefined : true) + }, + kit: { + // adapter-auto only supports some environments, see https://svelte.dev/docs/kit/adapter-auto for a list. + // If your environment is not supported, or you settled on a specific environment, switch out the adapter. + // See https://svelte.dev/docs/kit/adapters for more information about adapters. + adapter: adapter() + } +}; + +export default config; diff --git a/typesense-sveltekit-search-app/tsconfig.json b/typesense-sveltekit-search-app/tsconfig.json new file mode 100644 index 0000000..2c2ed3c --- /dev/null +++ b/typesense-sveltekit-search-app/tsconfig.json @@ -0,0 +1,20 @@ +{ + "extends": "./.svelte-kit/tsconfig.json", + "compilerOptions": { + "rewriteRelativeImportExtensions": true, + "allowJs": true, + "checkJs": true, + "esModuleInterop": true, + "forceConsistentCasingInFileNames": true, + "resolveJsonModule": true, + "skipLibCheck": true, + "sourceMap": true, + "strict": true, + "moduleResolution": "bundler" + } + // Path aliases are handled by https://svelte.dev/docs/kit/configuration#alias + // except $lib which is handled by https://svelte.dev/docs/kit/configuration#files + // + // To make changes to top-level options such as include and exclude, we recommend extending + // the generated config; see https://svelte.dev/docs/kit/configuration#typescript +} diff --git a/typesense-sveltekit-search-app/vite.config.ts b/typesense-sveltekit-search-app/vite.config.ts new file mode 100644 index 0000000..4bc0e08 --- /dev/null +++ b/typesense-sveltekit-search-app/vite.config.ts @@ -0,0 +1,10 @@ +import tailwindcss from '@tailwindcss/vite'; +import { sveltekit } from '@sveltejs/kit/vite'; +import { defineConfig } from 'vite'; + +export default defineConfig({ + plugins: [tailwindcss(), sveltekit()], + ssr: { + noExternal: ['typesense-instantsearch-adapter'] + } +}); From 1d509595365cdc532fe14f4258bf4e2757b53eb7 Mon Sep 17 00:00:00 2001 From: Nikhiladiga Date: Wed, 3 Jun 2026 09:37:50 +0530 Subject: [PATCH 14/15] [FEAT]: initialise Typesense AI movie search project with metadata seeding and semantic query parsing --- .../.chainlit/config.toml | 178 +++++++++++++ typesense-langchain-ai-search/.gitignore | 163 ++++++++++++ typesense-langchain-ai-search/README.md | 117 +++++++++ typesense-langchain-ai-search/app/__init__.py | 1 + .../app/core/__init__.py | 1 + typesense-langchain-ai-search/app/core/env.py | 13 + .../app/core/models.py | 29 +++ .../app/core/typesense.py | 18 ++ .../app/logic/__init__.py | 1 + .../app/logic/query_parser.py | 243 ++++++++++++++++++ .../app/logic/recommendation.py | 61 +++++ typesense-langchain-ai-search/app/main.py | 192 ++++++++++++++ .../app/services/__init__.py | 1 + .../app/services/motn.py | 106 ++++++++ .../requirements.txt | 10 + typesense-langchain-ai-search/seed.py | 175 +++++++++++++ 16 files changed, 1309 insertions(+) create mode 100644 typesense-langchain-ai-search/.chainlit/config.toml create mode 100644 typesense-langchain-ai-search/.gitignore create mode 100644 typesense-langchain-ai-search/README.md create mode 100644 typesense-langchain-ai-search/app/__init__.py create mode 100644 typesense-langchain-ai-search/app/core/__init__.py create mode 100644 typesense-langchain-ai-search/app/core/env.py create mode 100644 typesense-langchain-ai-search/app/core/models.py create mode 100644 typesense-langchain-ai-search/app/core/typesense.py create mode 100644 typesense-langchain-ai-search/app/logic/__init__.py create mode 100644 typesense-langchain-ai-search/app/logic/query_parser.py create mode 100644 typesense-langchain-ai-search/app/logic/recommendation.py create mode 100644 typesense-langchain-ai-search/app/main.py create mode 100644 typesense-langchain-ai-search/app/services/__init__.py create mode 100644 typesense-langchain-ai-search/app/services/motn.py create mode 100644 typesense-langchain-ai-search/requirements.txt create mode 100644 typesense-langchain-ai-search/seed.py diff --git a/typesense-langchain-ai-search/.chainlit/config.toml b/typesense-langchain-ai-search/.chainlit/config.toml new file mode 100644 index 0000000..7677129 --- /dev/null +++ b/typesense-langchain-ai-search/.chainlit/config.toml @@ -0,0 +1,178 @@ +[project] +# List of environment variables to be provided by each user to use the app. +user_env = [] + +# Duration (in seconds) during which the session is saved when the connection is lost +session_timeout = 3600 + +# Duration (in seconds) of the user session expiry +user_session_timeout = 1296000 # 15 days + +# Enable third parties caching (e.g., LangChain cache) +cache = false + +# Whether to persist user environment variables (API keys) to the database +# Set to true to store user env vars in DB, false to exclude them for security +persist_user_env = false + +# Whether to mask user environment variables (API keys) in the UI with password type +# Set to true to show API keys as ***, false to show them as plain text +mask_user_env = false + +# Authorized origins +allow_origins = ["*"] + +[features] +# Process and display HTML in messages. This can be a security risk (see https://stackoverflow.com/questions/19603097/why-is-it-dangerous-to-render-user-generated-html-or-javascript) +unsafe_allow_html = true + +# Process and display mathematical expressions. This can clash with "$" characters in messages. +latex = false + +# Enable rendering of user messages markdown +user_message_markdown = true + +# Autoscroll new user messages at the top of the window +user_message_autoscroll = true + +# Autoscroll new assistant messages +assistant_message_autoscroll = true + +# Automatically tag threads with the current chat profile (if a chat profile is used) +auto_tag_thread = true + +# Allow users to edit their own messages +edit_message = true + +# Allow users to share threads (backend + UI). Requires an app-defined on_shared_thread_view callback. +allow_thread_sharing = false + +# Enable favorite messages +favorites = false + +[features.slack] +# Add emoji reaction when message is received (requires reactions:write OAuth scope) +reaction_on_message_received = false + +# Authorize users to spontaneously upload files with messages +[features.spontaneous_file_upload] + enabled = true + # Define accepted file types using MIME types + # Examples: + # 1. For specific file types: + # accept = ["image/jpeg", "image/png", "application/pdf"] + # 2. For all files of certain type: + # accept = ["image/*", "audio/*", "video/*"] + # 3. For specific file extensions: + # accept = { "application/octet-stream" = [".xyz", ".pdb"] } + # Note: Using "*/*" is not recommended as it may cause browser warnings + accept = ["*/*"] + max_files = 20 + max_size_mb = 500 + +[features.audio] + # Enable audio features + enabled = false + # Sample rate of the audio + sample_rate = 24000 + +[features.mcp] + # Enable Model Context Protocol (MCP) features + enabled = false + +[features.mcp.sse] + enabled = true + +[features.mcp.streamable-http] + enabled = true + +[features.mcp.stdio] + enabled = true + # Only the executables in the allow list can be used for MCP stdio server. + # Only need the base name of the executable, e.g. "npx", not "/usr/bin/npx". + # Please don't comment this line for now, we need it to parse the executable name. + allowed_executables = [ "npx", "uvx" ] + +[UI] +# Name of the assistant. +name = "Assistant" + +# default_theme = "dark" + +# Force a specific language for all users (e.g., "en-US", "he-IL", "fr-FR") +# If not set, the browser's language will be used +# language = "en-US" + +# layout = "wide" + +# default_sidebar_state = "open" # Options: "open", "closed", "hidden" + +# Chat settings display location: "message_composer" (default) or "sidebar" (header) +# chat_settings_location = "message_composer" + +# Default state of chat settings sidebar when location is "sidebar" +# default_chat_settings_open = false + +# Whether to prompt user confirmation on clicking 'New Chat' +confirm_new_chat = true + +# Description of the assistant. This is used for HTML tags. +# description = "" + +# Chain of Thought (CoT) display mode. Can be "hidden", "tool_call" or "full". +cot = "full" + +# Specify a CSS file that can be used to customize the user interface. +# The CSS file can be served from the public directory or via an external link. +# custom_css = "/public/test.css" + +# Specify additional attributes for a custom CSS file +# custom_css_attributes = "media=\"print\"" + +# Specify a JavaScript file that can be used to customize the user interface. +# The JavaScript file can be served from the public directory. +# custom_js = "/public/test.js" + +# The style of alert boxes. Can be "classic" or "modern". +alert_style = "classic" + +# Specify additional attributes for custom JS file +# custom_js_attributes = "async type = \"module\"" + +# Custom login page image, relative to public directory or external URL +# login_page_image = "/public/custom-background.jpg" + +# Custom login page image filter (Tailwind internal filters, no dark/light variants) +# login_page_image_filter = "brightness-50 grayscale" +# login_page_image_dark_filter = "contrast-200 blur-sm" + +# Specify a custom meta URL (used for meta tags like og:url) +# custom_meta_url = "https://github.com/Chainlit/chainlit" + +# Specify a custom meta image url. +# custom_meta_image_url = "https://chainlit-cloud.s3.eu-west-3.amazonaws.com/logo/chainlit_banner.png" + +# Load assistant logo directly from URL. +logo_file_url = "" + +# Load assistant avatar image directly from URL. +default_avatar_file_url = "" + +# Avatar size in pixels (default: 20). +# avatar_size = 20 + +# Specify a custom build directory for the frontend. +# This can be used to customize the frontend code. +# Be careful: If this is a relative path, it should not start with a slash. +# custom_build = "./public/build" + +# Specify optional one or more custom links in the header. +# [[UI.header_links]] +# name = "Issues" +# display_name = "Report Issue" +# icon_url = "https://avatars.githubusercontent.com/u/128686189?s=200&v=4" +# url = "https://github.com/Chainlit/chainlit/issues" +# target = "_blank" (default) # Optional: "_self", "_parent", "_top". + +[meta] +generated_by = "2.11.1" diff --git a/typesense-langchain-ai-search/.gitignore b/typesense-langchain-ai-search/.gitignore new file mode 100644 index 0000000..3d13cc4 --- /dev/null +++ b/typesense-langchain-ai-search/.gitignore @@ -0,0 +1,163 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so they can be injected with +# other data. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nosenv/ +.pytest_cache/ +.mypy_cache/ +.dmypy.json +dmypy.json +.hypothesis/ +.run/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to share your .python-version. +# For an app, they are usually ignored. +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if used, it should be kept. +# But we can ignore Pipenv's own virtual environments. +# .venv + +# Poetry +# Poetry creates virtual environments in a system directory by default, +# but if configured to create it in the project, ignore it. +# .venv + +# pdm +# Similar to Pipenv and Poetry, but with __pypackages__ +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath Parsed Files +*.sage.py + +# Environments +.env +.env.local +.env.development.local +.env.test.local +.env.production.local +.env.* + +# Virtual Environments +.venv/ +venv/ +ENV/ +env/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# OS-specific files +.DS_Store +.DS_Store? +._* +.Spotlight-V100 +.Trashes +ehthumbs.db +Thumbs.db + +# Editor/IDE files +.vscode/ +.idea/ +*.suo +*.ntvs* +*.njsproj +*.sln +*.swp + +# Chainlit specific +.files/ +.chainlit/translations/ + +# Datasets +data diff --git a/typesense-langchain-ai-search/README.md b/typesense-langchain-ai-search/README.md new file mode 100644 index 0000000..03d7d68 --- /dev/null +++ b/typesense-langchain-ai-search/README.md @@ -0,0 +1,117 @@ +# LangChain AI Movie Search with Typesense + +A conversational AI-powered movie search and recommendation chat assistant. Features structured natural language query parsing, strict metadata-driven hybrid vector search via Typesense, parallel live streaming availability enrichment from the Movie of the Night (MOTN) API, conversational recommendation synthesis, and a real-time chat interface built with Chainlit. + +--- + +## Tech Stack + +- **Python 3.10+** +- **LangChain** (for AI orchestration) +- **Typesense** (for hybrid vector & keyword search) +- **Chainlit** (for the real-time chat UI) +- **OpenAI** (`gpt-4o-mini` & `text-embedding-3-small` for parser/recommendation engines) +- **Docker** (for running Typesense) + +--- + +## Prerequisites + +- **Python 3.10+** installed +- **Docker** (to run Typesense) +- **OpenAI API Key** +- **Movie of the Night API Key** (RapidAPI) +- **Kaggle TMDB 5000 Movies Dataset** + +--- + +## Quick Start + +### 1. Clone the repository +```bash +git clone https://github.com/typesense/code-samples.git +cd typesense-langchain-ai-search +``` + +### 2. Install dependencies +Create a virtual environment and install the required Python packages: +```bash +python3 -m venv .venv +source .venv/bin/activate +pip install -r requirements.txt +``` + +### 3. Start Typesense +Start Typesense locally using Docker: +```bash +docker run -d \ + -p 8108:8108 \ + -v typesense-data:/data \ + typesense/typesense:26.0 \ + --data-dir /data \ + --api-key=xyz \ + --enable-cors +``` + +### 4. Configure environment variables +Create a `.env` file in the root directory: +```env +# Typesense Configuration +TYPESENSE_HOST=localhost +TYPESENSE_PORT=8108 +TYPESENSE_PROTOCOL=http +TYPESENSE_API_KEY=xyz +TYPESENSE_COLLECTION_NAME=movies + +# OpenAI Configuration +OPENAI_API_KEY=your-openai-api-key +LLM_MODEL=gpt-4o-mini +LLM_BASE_URL=https://api.openai.com/v1 + +# Movie of the Night API Configuration +MOTN_API_KEY=your-movie-of-the-night-api-key +``` + +### 5. Ingest the dataset +1. Download `tmdb_5000_movies.csv` and `tmdb_5000_credits.csv` from the [TMDB 5000 Movie Dataset](https://www.kaggle.com/datasets/tmdb/tmdb-movie-metadata) on Kaggle. +2. Create a folder named `data/` at the root of the project and place both CSV files inside it. +3. Run the seeding script to clean, vectorize, and import the movies into Typesense: +```bash +python seed.py +``` +*(Note: When seeding large datasets in production, be mindful of OpenAI embedding costs. Typesense also supports built-in, local machine learning models like `SentenceTransformers` to generate embeddings locally).* + +### 6. Run the chat assistant +Start the Chainlit server: +```bash +chainlit run app/main.py --watch +``` +Open `http://localhost:8000` in your browser. You can now chat with your movie database using natural language! + +--- + +## Project Structure + +```text +├── app/ +│ ├── core/ +│ │ ├── __init__.py +│ │ ├── env.py # Environment variable utility functions +│ │ ├── models.py # Model configurations (LLM & Embeddings) +│ │ └── typesense.py # Typesense client connection pool +│ ├── logic/ +│ │ ├── __init__.py +│ │ ├── query_parser.py # Pydantic parsing of query into structured filters +│ │ └── recommendation.py # AI conversational recommendation synthesis +│ ├── services/ +│ │ ├── __init__.py +│ │ └── motn.py # LangChain @tool fetching live streaming providers +│ ├── public/ +│ │ └── langchain.png # UI Assets +│ └── main.py # Chainlit handlers & query orchestrator +├── data/ # Datasets folder (git-ignored) +├── .gitignore +├── requirements.txt +├── seed.py # Cleaning & ingestion script +└── README.md +``` \ No newline at end of file diff --git a/typesense-langchain-ai-search/app/__init__.py b/typesense-langchain-ai-search/app/__init__.py new file mode 100644 index 0000000..d90f89b --- /dev/null +++ b/typesense-langchain-ai-search/app/__init__.py @@ -0,0 +1 @@ +# Marks app directory as package diff --git a/typesense-langchain-ai-search/app/core/__init__.py b/typesense-langchain-ai-search/app/core/__init__.py new file mode 100644 index 0000000..7120315 --- /dev/null +++ b/typesense-langchain-ai-search/app/core/__init__.py @@ -0,0 +1 @@ +# Marks app/core directory as package diff --git a/typesense-langchain-ai-search/app/core/env.py b/typesense-langchain-ai-search/app/core/env.py new file mode 100644 index 0000000..df3d290 --- /dev/null +++ b/typesense-langchain-ai-search/app/core/env.py @@ -0,0 +1,13 @@ +import os +from dotenv import load_dotenv + +# Locate and load the .env file once globally +dotenv_path = os.path.join(os.getcwd(), ".env") +if not os.path.exists(dotenv_path): + # Go up 3 levels from app/core/env.py to reach root + dotenv_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), ".env") +load_dotenv(dotenv_path=dotenv_path, override=True) + +def get_env(key: str, default: any = None) -> any: + """Retrieves the value of an environment variable, returning a default if not found.""" + return os.getenv(key, default) diff --git a/typesense-langchain-ai-search/app/core/models.py b/typesense-langchain-ai-search/app/core/models.py new file mode 100644 index 0000000..bab2985 --- /dev/null +++ b/typesense-langchain-ai-search/app/core/models.py @@ -0,0 +1,29 @@ +import numpy as np +from app.core.env import get_env + +# Configure OpenAI Settings +LLM_BASE_URL = get_env("LLM_BASE_URL", "https://api.openai.com/v1") +LLM_MODEL = get_env("LLM_MODEL", "gpt-4o-mini") +LLM_API_KEY = get_env("OPENAI_API_KEY") +EMBEDDING_DIM = 1536 + +class OpenAIEmbeddingAdapter: + def __init__(self, api_key: str, base_url: str): + from langchain_openai import OpenAIEmbeddings + self._embeddings = OpenAIEmbeddings( + model="text-embedding-3-small", + openai_api_key=api_key, + openai_api_base=base_url + ) + + def encode(self, text: str | list[str], *args, **kwargs): + if isinstance(text, str): + res = self._embeddings.embed_query(text) + return np.array(res) + elif isinstance(text, list): + res = self._embeddings.embed_documents(text) + return np.array(res) + else: + raise TypeError("Expected string or list of strings") + +model = OpenAIEmbeddingAdapter(api_key=LLM_API_KEY, base_url=LLM_BASE_URL) diff --git a/typesense-langchain-ai-search/app/core/typesense.py b/typesense-langchain-ai-search/app/core/typesense.py new file mode 100644 index 0000000..761aaa4 --- /dev/null +++ b/typesense-langchain-ai-search/app/core/typesense.py @@ -0,0 +1,18 @@ +import typesense +from app.core.env import get_env + +# Typesense Connection Details +TYPESENSE_HOST = get_env("TYPESENSE_HOST", "localhost") +TYPESENSE_PORT = get_env("TYPESENSE_PORT", "8108") +TYPESENSE_API_KEY = get_env("TYPESENSE_API_KEY", get_env("PUBLIC_TYPESENSE_API_KEY", "xyz")) + +# Initialize Typesense Client +client = typesense.Client({ + 'nodes': [{ + 'host': TYPESENSE_HOST, + 'port': TYPESENSE_PORT, + 'protocol': 'http' + }], + 'api_key': TYPESENSE_API_KEY, + 'connection_timeout_seconds': 120 +}) diff --git a/typesense-langchain-ai-search/app/logic/__init__.py b/typesense-langchain-ai-search/app/logic/__init__.py new file mode 100644 index 0000000..1ebdcbd --- /dev/null +++ b/typesense-langchain-ai-search/app/logic/__init__.py @@ -0,0 +1 @@ +# Marks app/logic directory as package diff --git a/typesense-langchain-ai-search/app/logic/query_parser.py b/typesense-langchain-ai-search/app/logic/query_parser.py new file mode 100644 index 0000000..7071b98 --- /dev/null +++ b/typesense-langchain-ai-search/app/logic/query_parser.py @@ -0,0 +1,243 @@ +import json +from langchain_openai import ChatOpenAI +from langchain_core.prompts import ChatPromptTemplate +from langchain_core.output_parsers import StrOutputParser + +from app.core.models import LLM_MODEL, LLM_BASE_URL, LLM_API_KEY + +from pydantic import BaseModel, Field +from typing import List, Optional, Literal + +from langchain_core.output_parsers import PydanticOutputParser + +class QueryFilters(BaseModel): + cast: Optional[List[str]] = Field( + default=None, + description="List of specific actor or actress names mentioned in the query." + ) + cast_operator: Literal["AND", "OR"] = Field( + default="AND", + description="Logical relationship between cast members: 'AND' if all/both must match, 'OR' if any/either can match." + ) + director: Optional[List[str]] = Field( + default=None, + description="List of specific director names mentioned." + ) + director_operator: Literal["AND", "OR"] = Field( + default="AND", + description="Logical relation for directors." + ) + genre: Optional[List[str]] = Field( + default=None, + description="List of specific genres mentioned. MUST be mapped strictly to allowed database categories: 'Drama', 'Comedy', 'Thriller', 'Action', 'Romance', 'Adventure', 'Crime', 'Science Fiction', 'Horror', 'Family', 'Fantasy', 'Mystery', 'Animation', 'History', 'Music', 'War', 'Documentary', 'Western', 'Foreign', 'TV Movie'. (e.g., map 'Animated' to 'Animation', and 'Sci-Fi' to 'Science Fiction')." + ) + genre_operator: Literal["AND", "OR"] = Field( + default="AND", + description="Logical relation for genres." + ) + year: Optional[str] = Field( + default=None, + description="Specific release year mentioned." + ) + exclude_titles: Optional[List[str]] = Field( + default=None, + description="List of specific movie titles to exclude, or reference movies (e.g. 'movies like Interstellar' -> ['Interstellar'])." + ) + +class MovieSearchQuery(BaseModel): + filters: QueryFilters = Field( + description="Extracted hard filter constraints." + ) + semantic_query: Optional[str] = Field( + default=None, + description="Thematic description, plot elements, mood, tone. Do NOT include cast names, director names, or genres here." + ) + + +# Mapping of common variations of genres to the exact database values +GENRE_MAP = { + "animated": "Animation", + "animation": "Animation", + "anime": "Animation", + "sci-fi": "Science Fiction", + "scifi": "Science Fiction", + "science fiction": "Science Fiction", + "science-fiction": "Science Fiction", + "sci fi": "Science Fiction", + "tv movie": "TV Movie", + "tv-movie": "TV Movie", + "tvmovie": "TV Movie", + "romantic": "Romance", + "romance": "Romance", + "drama": "Drama", + "comedy": "Comedy", + "thriller": "Thriller", + "action": "Action", + "adventure": "Adventure", + "crime": "Crime", + "horror": "Horror", + "family": "Family", + "fantasy": "Fantasy", + "mystery": "Mystery", + "history": "History", + "music": "Music", + "war": "War", + "documentary": "Documentary", + "western": "Western", + "foreign": "Foreign" +} + + +def parse_query(user_query: str) -> dict: + """ + Uses LangChain and PydanticOutputParser to parse the user's query into concrete filters + and semantic search themes. + """ + try: + llm = ChatOpenAI( + model=LLM_MODEL, + temperature=0.0, + openai_api_key=LLM_API_KEY, + base_url=LLM_BASE_URL + ) + + pydantic_parser = PydanticOutputParser(pydantic_object=MovieSearchQuery) + + prompt = ChatPromptTemplate.from_messages([ + ("system", "You are a movie search query parser. Extract hard filters and semantic search themes.\n" + "Your output must conform to the JSON schema instructions below:\n" + "{format_instructions}\n" + "Do not include actor names, director names, or genres in the semantic query.\n" + "If the user asks for movies 'like' or 'similar to' a specific movie, add that movie to exclude_titles.\n" + "Do not infer or guess values; only extract what is explicitly mentioned.\n" + "IMPORTANT: Allowed genres are: 'Drama', 'Comedy', 'Thriller', 'Action', 'Romance', " + "'Adventure', 'Crime', 'Science Fiction', 'Horror', 'Family', 'Fantasy', 'Mystery', " + "'Animation', 'History', 'Music', 'War', 'Documentary', 'Western', 'Foreign', 'TV Movie'. " + "You must normalize extracted genres to match these database names exactly. " + "For example, map 'Animated' to 'Animation', 'Sci-fi' to 'Science Fiction', and 'Romance' to 'Romance'.\n" + "Return ONLY the raw JSON output matching the schema with no extra text."), + ("user", "Query: {query}") + ]) + + chain = prompt | llm | StrOutputParser() + result = chain.invoke({ + "query": user_query, + "format_instructions": pydantic_parser.get_format_instructions() + }) + + # Strip markdown fences if LLM adds them despite instructions + cleaned = result.strip().removeprefix("```json").removeprefix("```").removesuffix("```").strip() + parsed_obj = pydantic_parser.parse(cleaned) + parsed = parsed_obj.model_dump() + print(f"[Query Parser] Structured: '{user_query}' → {parsed}") + return parsed + + except Exception as e: + print(f"[WARNING] Structured query parsing failed: {e}. Falling back to raw query.") + return { + "filters": {}, + "semantic_query": user_query + } + + +def build_filter_string(filters: dict, user_query: str = "") -> str | None: + """ + Converts extracted filter dict into a Typesense filter_by string. + + Example output: + 'cast:=["Will Smith"] && cast:=["Tommy Lee Jones"] && genres:=["Action"]' + + Returns None if no filters are present. + """ + conditions = [] + q_lower = user_query.lower() + + # Handle cast + cast = filters.get("cast") + cast_operator = filters.get("cast_operator", "AND") + if cast: + if isinstance(cast, str): + cast_list = [c.strip() for c in cast.split(",") if c.strip() and c.strip().lower() != "null"] + elif isinstance(cast, list): + cast_list = [c for c in cast if c and str(c).lower() != "null"] + else: + cast_list = [] + + if cast_list: + if cast_operator == "OR" or " or " in q_lower: + quoted_actors = ", ".join(f'"{actor}"' for actor in cast_list) + conditions.append(f'cast:=[{quoted_actors}]') + else: + for actor in cast_list: + conditions.append(f'cast:=["{actor}"]') + + # Handle director + director = filters.get("director") + director_operator = filters.get("director_operator", "AND") + if director: + if isinstance(director, str): + director_list = [d.strip() for d in director.split(",") if d.strip() and d.strip().lower() != "null"] + elif isinstance(director, list): + director_list = [d for d in director if d and str(d).lower() != "null"] + else: + director_list = [] + + if director_list: + if director_operator == "OR" or " or " in q_lower: + quoted_dirs = ", ".join(f'"{dir_name}"' for dir_name in director_list) + conditions.append(f'director:=[{quoted_dirs}]') + else: + for dir_name in director_list: + conditions.append(f'director:="{dir_name}"') + + # Handle genre + genre = filters.get("genre") + genre_operator = filters.get("genre_operator", "AND") + if genre: + if isinstance(genre, str): + genre_list = [g.strip() for g in genre.split(",") if g.strip() and g.strip().lower() != "null"] + elif isinstance(genre, list): + genre_list = [g for g in genre if g and str(g).lower() != "null"] + else: + genre_list = [] + + if genre_list: + normalized_genres = [] + for g in genre_list: + norm = GENRE_MAP.get(g.strip().lower(), g.strip()) + # Capitalize nicely if not found in mapping dictionary + if norm not in GENRE_MAP.values(): + norm = norm.title() + normalized_genres.append(norm) + + if genre_operator == "OR" or " or " in q_lower: + quoted_genres = ", ".join(f'"{g_name}"' for g_name in normalized_genres) + conditions.append(f'genres:=[{quoted_genres}]') + else: + for g_name in normalized_genres: + conditions.append(f'genres:=["{g_name}"]') + + # Handle year + year = filters.get("year") + if year and str(year).lower() != "null": + try: + conditions.append(f'release_year:={int(year)}') + except ValueError: + pass # Ignore malformed year + + # Handle exclude_titles + exclude_titles = filters.get("exclude_titles") + if exclude_titles: + if isinstance(exclude_titles, str): + exclude_list = [t.strip() for t in exclude_titles.split(",") if t.strip() and t.strip().lower() != "null"] + elif isinstance(exclude_titles, list): + exclude_list = [t for t in exclude_titles if t and str(t).lower() != "null"] + else: + exclude_list = [] + + for t_name in exclude_list: + conditions.append(f'title:!="{t_name}"') + + result = " && ".join(conditions) if conditions else None + print(f"[Filter Builder] filter_by → {result}") + return result diff --git a/typesense-langchain-ai-search/app/logic/recommendation.py b/typesense-langchain-ai-search/app/logic/recommendation.py new file mode 100644 index 0000000..09e8d34 --- /dev/null +++ b/typesense-langchain-ai-search/app/logic/recommendation.py @@ -0,0 +1,61 @@ +from langchain_openai import ChatOpenAI +from langchain_core.prompts import ChatPromptTemplate +from langchain_core.output_parsers import StrOutputParser + +from app.core.models import LLM_MODEL, LLM_BASE_URL, LLM_API_KEY + +def synthesize_recommendations(user_query: str, movies_data: list) -> str: + """Uses LLM to write a personalized conversational recommendation response.""" + movies_text = "" + for idx, movie in enumerate(movies_data, 1): + providers = movie.get("watch_providers", {}) + streaming = ", ".join(providers.get("streaming", [])) if providers.get("streaming") else "Not streaming (Rent/Buy only)" + rent = ", ".join(providers.get("rent", [])) if providers.get("rent") else "None" + + movies_text += f"{idx}. {movie['title']} ({movie.get('release_year', 'N/A')})\n" + movies_text += f" Director: {movie.get('director', 'N/A')}\n" + movies_text += f" Cast: {', '.join(movie.get('cast', []))}\n" + movies_text += f" Overview: {movie['overview']}\n" + movies_text += f" Streaming: {streaming}\n" + movies_text += f" Rent/Buy: {rent}\n\n" + + try: + llm = ChatOpenAI( + model=LLM_MODEL, + temperature=0.7, + openai_api_key=LLM_API_KEY, + base_url=LLM_BASE_URL + ) + + prompt = ChatPromptTemplate.from_messages([ + ("system", "You are CineSearch AI, a professional movie concierge. " + "You will synthesize the search results from the database into a friendly, " + "cinematic recommendation response. Explain why these movies fit the user's request. " + "Highlight where they are streaming (subscription) or if they are only available for rent/buy. " + "Be conversational, engaging, and professional. Use markdown formatting."), + ("user", "User Request: {query}\n\nRetrieved Movies & Live Watch Providers:\n{movies}") + ]) + + chain = prompt | llm | StrOutputParser() + response = chain.invoke({"query": user_query, "movies": movies_text}) + return response + + except Exception as e: + print(f"[WARNING] LLM synthesis failed: {e}. Using rule-based fallback synthesis.") + + fallback = f"### Here are the top movie recommendations for your query: *\"{user_query}\"*\n\n" + for idx, movie in enumerate(movies_data, 1): + providers = movie.get("watch_providers", {}) + streaming = providers.get("streaming", []) + rent = providers.get("rent", []) + + stream_info = f"Streaming on **{', '.join(streaming)}**" if streaming else "Not available on subscription streaming services." + rent_info = f" Available to rent/buy on **{', '.join(rent[:4])}**." if rent else "" + + fallback += f"**{idx}. {movie['title']}** ({movie.get('release_year', 'N/A')})\n" + fallback += f"- *Director*: {movie.get('director', 'N/A')} | *Cast*: {', '.join(movie.get('cast', []))}\n" + fallback += f"- *Overview*: {movie['overview']}\n" + fallback += f"- *Where to watch*: {stream_info}{rent_info}\n\n" + + fallback += "\n*(Note: LLM synthesis is running in rule-based fallback mode. Please update the OPENAI_API_KEY in your .env file to enable full conversational AI features.)*" + return fallback diff --git a/typesense-langchain-ai-search/app/main.py b/typesense-langchain-ai-search/app/main.py new file mode 100644 index 0000000..3abd880 --- /dev/null +++ b/typesense-langchain-ai-search/app/main.py @@ -0,0 +1,192 @@ +import os +import sys +import base64 + +# Prevent Engine.IO socket payload limit errors during fast hot-reloads +from engineio.payload import Payload +Payload.max_decode_packets = 256 + +# Add project root to sys.path so 'app' imports work when executed via chainlit CLI +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +import chainlit as cl +from app.core.typesense import client +from app.core.models import model +from app.logic.query_parser import parse_query, build_filter_string +from app.services.motn import fetch_motn_info +from app.logic.recommendation import synthesize_recommendations +from concurrent.futures import ThreadPoolExecutor + + +# --------------------------------------------------------------------------- +# Chainlit Handlers +# --------------------------------------------------------------------------- +# @cl.on_chat_start +# async def start(): +# # Read and send chainlit.md content dynamically based on this file's location +# welcome_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "chainlit.md") +# with open(welcome_path, "r", encoding="utf-8") as f: +# content = f.read() +# await cl.Message(content=content).send() + +@cl.on_chat_start +async def start(): + content = f""" +
+

AI Powered Movie Search

+ +
+ +--- +### Try searching for: +* *Will Smith movies with aliens and guns* +* *a cool sci-fi movie similar to Interstellar* +* *mind-bending thrillers directed by Christopher Nolan* +* *heartwarming animations about family* +""" + await cl.Message(content=content).send() + +@cl.on_message +async def main(message: cl.Message): + user_query = message.content.strip() + if not user_query: + return + + # ------------------------------------------------------------------ + # Step 1 — Parse query into hard filters + semantic theme + # ------------------------------------------------------------------ + async with cl.Step(name="Parsing query") as step: + step.input = user_query + parsed = parse_query(user_query) + + semantic_query = parsed.get("semantic_query") + if not semantic_query or str(semantic_query).lower().strip() in ("null", "none"): + semantic_query = user_query + filters = parsed.get("filters", {}) + filter_by = build_filter_string(filters, user_query) + + active_filters = {k: v for k, v in filters.items() if v} + filter_summary = f"Filters: {active_filters}" if active_filters else "No hard filters detected." + step.output = f"Semantic query: '{semantic_query}'\n{filter_summary}" + + # ------------------------------------------------------------------ + # Step 2 — Embed semantic query + run Typesense hybrid search + # ------------------------------------------------------------------ + async with cl.Step(name="Searching movie database") as step: + # Embed only the semantic/thematic part of the query + query_vector = model.encode(semantic_query).tolist() + + # Build Typesense search request + # k:20 retrieves more candidates; flat_search_cutoff:20 forces exact ranking + # when the filtered set is small (e.g. only 20 Will Smith movies exist) + search_params = { + 'collection': 'movies', + 'q': '*', + 'vector_query': f'embedding:([{",".join(map(str, query_vector))}], k:20, flat_search_cutoff: 20)' + } + + # Attach hard filters if present — this narrows candidates BEFORE vector ranking + if filter_by: + search_params['filter_by'] = filter_by + + try: + search_requests = {'searches': [search_params]} + response = client.multi_search.perform(search_requests, {}) + search_results = response['results'][0] + hits = search_results.get("hits", [])[:5] # Top 5 from the broader k:20 pool + step.input = f"Semantic: '{semantic_query}' | filter_by: {filter_by or 'None'}" + step.output = f"Found {len(hits)} matching documents in Typesense." + except Exception as e: + step.output = f"Error during vector search: {e}" + await cl.Message(content=f"❌ Error performing search: {e}").send() + return + + if not hits: + # Provide a helpful message if filters were too restrictive + no_result_msg = f"Sorry, I couldn't find any movies matching: *\"{user_query}\"*" + if filter_by: + no_result_msg += f"\n\n> ℹ️ Search was filtered by: `{filter_by}`. Try rephrasing if this seems too strict." + await cl.Message(content=no_result_msg).send() + return + + # ------------------------------------------------------------------ + # Step 3 — Enrich results with MOTN watch providers + posters + # ------------------------------------------------------------------ + async with cl.Step(name="Retrieving streaming availability") as step: + + movies = [] + + # Run MOTN info fetches in parallel + with ThreadPoolExecutor(max_workers=len(hits)) as executor: + # Map future to corresponding hit document + future_to_hit = {} + for hit in hits: + doc = hit.get("document", {}) + movie_id = doc.get("id") + future = executor.submit(fetch_motn_info.invoke, {"movie_id": movie_id}) + future_to_hit[future] = hit + + # Retrieve results in order of submissions + for future in future_to_hit: + hit = future_to_hit[future] + doc = hit.get("document", {}) + try: + motn_info = future.result() + except Exception as e: + print(f"[WARNING] Failed to fetch parallel MOTN info: {e}") + motn_info = { + "poster_url": None, + "watch_providers": {"streaming": [], "rent": [], "buy": []} + } + + movie_item = { + "title": doc.get("title"), + "overview": doc.get("overview"), + "genres": doc.get("genres", []), + "release_year": doc.get("release_year"), + "cast": doc.get("cast", []), + "director": doc.get("director"), + "poster_url": motn_info["poster_url"], + "watch_providers": motn_info["watch_providers"], + "score": hit.get("vector_distance") + } + movies.append(movie_item) + + step.output = f"Fetched watch providers and poster details for {len(movies)} movies in parallel." + + # ------------------------------------------------------------------ + # Step 4 — Format and send final response + # ------------------------------------------------------------------ + response_content = "### Here are movies that I recommend:\n\n" + + for movie in movies: + providers = movie.get("watch_providers", {}) + streaming = providers.get("streaming", []) + rent = providers.get("rent", []) + + stream_str = ", ".join(streaming) if streaming else "Not available on subscription streaming" + rent_str = ", ".join(rent[:4]) if rent else "Not listed" + + response_content += f"#### 🎥 {movie['title']} ({movie.get('release_year', 'N/A')})\n" + + if movie.get("poster_url"): + response_content += f"![Poster]({movie['poster_url']})\n\n" + + response_content += f"**Director:** {movie.get('director', 'Unknown')} | **Genres:** {', '.join(movie.get('genres', []))}\n" + response_content += f"**Cast:** {', '.join(movie.get('cast', []))}\n" + response_content += f"**Relevance Score:** {(1 - movie['score']):.3f}\n" + response_content += f"**Synopsis:** {movie['overview']}\n\n" + response_content += f"📺 **Stream (US):** {stream_str}\n" + response_content += f"💳 **Rent/Buy:** {rent_str}\n\n" + response_content += "---\n\n" + + await cl.Message(content=response_content).send() diff --git a/typesense-langchain-ai-search/app/services/__init__.py b/typesense-langchain-ai-search/app/services/__init__.py new file mode 100644 index 0000000..835aae3 --- /dev/null +++ b/typesense-langchain-ai-search/app/services/__init__.py @@ -0,0 +1 @@ +# Marks app/services directory as package diff --git a/typesense-langchain-ai-search/app/services/motn.py b/typesense-langchain-ai-search/app/services/motn.py new file mode 100644 index 0000000..56bb838 --- /dev/null +++ b/typesense-langchain-ai-search/app/services/motn.py @@ -0,0 +1,106 @@ +import time +import requests +from app.core.env import get_env +from urllib3.util import Retry +from requests.adapters import HTTPAdapter + +from langchain_core.tools import tool + +def _make_motn_session() -> requests.Session: + """Creates a fresh Movie of the Night session with retry strategy""" + session = requests.Session() + session.headers.update({ + "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", + "accept": "application/json" + }) + retry_strategy = Retry( + total=3, + backoff_factor=1.0, + status_forcelist=[429, 500, 502, 503, 504], + allowed_methods=["GET"], + raise_on_status=False + ) + adapter = HTTPAdapter(max_retries=retry_strategy) + session.mount("https://", adapter) + session.mount("http://", adapter) + return session + +def _motn_get(url: str, headers: dict, max_retries: int = 3) -> requests.Response | None: + """ + GET with manual retry for ConnectionResetError. + Creates a fresh session per retry instead of reusing a potentially + stale pooled connection. + """ + for attempt in range(max_retries): + session = _make_motn_session() + try: + resp = session.get(url, headers=headers, timeout=8) + return resp + except (ConnectionError, requests.exceptions.ConnectionError) as e: + if attempt < max_retries - 1: + wait = 1.0 * (attempt + 1) + print(f"[MOTN] Connection reset on attempt {attempt + 1}, retrying in {wait}s...") + time.sleep(wait) + else: + print(f"[MOTN] All {max_retries} attempts failed for {url}: {e}") + return None + finally: + session.close() + return None + +@tool +def fetch_motn_info(movie_id: str) -> dict: + """Fetches watch providers (streaming/rent/buy) and poster paths from the Movie of the Night API using the movie's TMDB ID.""" + motn_key = get_env("MOTN_API_KEY") + info = { + "poster_url": None, + "watch_providers": { + "streaming": [], + "rent": [], + "buy": [] + } + } + + print(f"[MOTN] Fetching info for movie_id={movie_id}") + + if not motn_key or motn_key == "1234": + return info + + headers = { + "X-API-Key": motn_key + } + + try: + url = f"https://api.movieofthenight.com/v4/shows/movie/{movie_id}" + resp = _motn_get(url, headers) + if resp and resp.status_code == 200: + data = resp.json() + + # Fetch poster + image_set = data.get("imageSet", {}) + vertical_poster = image_set.get("verticalPoster", {}) + info["poster_url"] = vertical_poster.get("w480") or vertical_poster.get("w360") or vertical_poster.get("original") + + # Fetch watch providers for US + streaming_options = data.get("streamingOptions", {}) + us_providers = streaming_options.get("us", []) + + for provider in us_providers: + service_name = provider.get("service", {}).get("name", "") + stream_type = provider.get("type", "") + + if stream_type == "subscription": + info["watch_providers"]["streaming"].append(service_name) + elif stream_type == "rent": + info["watch_providers"]["rent"].append(service_name) + elif stream_type == "buy": + info["watch_providers"]["buy"].append(service_name) + + # Deduplicate provider lists + for k in info["watch_providers"]: + info["watch_providers"][k] = list(set(info["watch_providers"][k])) + + except Exception as e: + print(f"[WARNING] Failed to fetch MOTN info for movie {movie_id}: {e}") + + return info diff --git a/typesense-langchain-ai-search/requirements.txt b/typesense-langchain-ai-search/requirements.txt new file mode 100644 index 0000000..8c0a565 --- /dev/null +++ b/typesense-langchain-ai-search/requirements.txt @@ -0,0 +1,10 @@ +pandas +typesense +sentence-transformers +langchain +langchain-openai +fastapi +uvicorn +requests +python-dotenv +chainlit \ No newline at end of file diff --git a/typesense-langchain-ai-search/seed.py b/typesense-langchain-ai-search/seed.py new file mode 100644 index 0000000..4958c55 --- /dev/null +++ b/typesense-langchain-ai-search/seed.py @@ -0,0 +1,175 @@ +import os +import json +import pandas as pd +import torch +import typesense +from dotenv import load_dotenv +from app.core.typesense import client +from app.core.models import model, EMBEDDING_DIM + +def parse_genres(x): + try: + if pd.isna(x) or not x: + return [] + data = json.loads(x) + return [item['name'] for item in data] + except Exception: + return [] + +def parse_cast(x): + try: + if pd.isna(x) or not x: + return [] + data = json.loads(x) + # Limit to top 3 cast members to save memory + return [item['name'] for item in data[:3]] + except Exception: + return [] + +def parse_director(x): + try: + if pd.isna(x) or not x: + return "" + data = json.loads(x) + for item in data: + if item.get('job') == 'Director': + return item.get('name', '') + return "" + except Exception: + return "" + +def parse_year(x): + try: + if pd.isna(x) or not x: + return None + parts = str(x).split('-') + if len(parts) > 0 and parts[0].isdigit(): + return int(parts[0]) + return None + except Exception: + return None + +def main(): + # 1. Load the Datasets + print("Loading TMDB CSV files...") + movies_path = "data/tmdb_5000_movies.csv" + credits_path = "data/tmdb_5000_credits.csv" + + if not os.path.exists(movies_path) or not os.path.exists(credits_path): + print("Error: CSV files not found in data/ folder!") + return + + movies_df = pd.read_csv(movies_path) + credits_df = pd.read_csv(credits_path) + + # Keep only the essential columns before merging to minimize RAM usage + movies_df = movies_df[['id', 'title', 'overview', 'genres', 'release_date']] + credits_df = credits_df[['movie_id', 'cast', 'crew']] + + # Merge on movie ID + print("Merging datasets...") + df = pd.merge(movies_df, credits_df, left_on='id', right_on='movie_id') + + # Process and clean fields + print("Processing and cleaning movie metadata...") + df['genres'] = df['genres'].apply(parse_genres) + df['cast'] = df['cast'].apply(parse_cast) + df['director'] = df['crew'].apply(parse_director) + df['release_year'] = df['release_date'].apply(parse_year) + + # Fill missing values + df['overview'] = df['overview'].fillna("") + df['title'] = df['title'].fillna("") + + # Drop columns no longer needed + df = df.drop(columns=['release_date', 'movie_id', 'crew']) + + # 2. Create or Recreate Typesense Collection + print("Setting up Typesense collection schema...") + schema = { + 'name': 'movies', + 'fields': [ + {'name': 'id', 'type': 'string'}, + {'name': 'title', 'type': 'string'}, + {'name': 'overview', 'type': 'string', 'optional': True}, + {'name': 'genres', 'type': 'string[]', 'facet': True, 'optional': True}, + {'name': 'release_year', 'type': 'int32', 'facet': True, 'sort': True, 'optional': True}, + {'name': 'cast', 'type': 'string[]', 'facet': True, 'optional': True}, + {'name': 'director', 'type': 'string', 'facet': True, 'optional': True}, + {'name': 'embedding', 'type': 'float[]', 'num_dim': EMBEDDING_DIM} + ] + } + + try: + client.collections['movies'].delete() + print("Deleted existing 'movies' collection.") + except Exception: + pass + + client.collections.create(schema) + print("Created 'movies' collection.") + + # 4. Generate Embeddings and Seed Data + print("Generating embeddings and seeding collection...") + documents = [] + total_movies = len(df) + + for i, row in df.iterrows(): + # Build text string to represent the movie semantically + genres_str = ", ".join(row['genres']) if row['genres'] else "" + cast_str = ", ".join(row['cast']) if row['cast'] else "" + + texts = [] + texts.append(f"Title: {row['title']}") + if row['overview']: + texts.append(f"Overview: {row['overview']}") + if genres_str: + texts.append(f"Genres: {genres_str}") + if cast_str: + texts.append(f"Cast: {cast_str}") + if row['director']: + texts.append(f"Director: {row['director']}") + + doc_text = ". ".join(texts) + "." + + # Prepare Typesense document + doc = { + 'id': str(row['id']), + 'title': str(row['title']), + 'overview': str(row['overview']), + 'genres': list(row['genres']), + 'cast': list(row['cast']), + 'director': str(row['director']) + } + + if row['release_year'] is not None and not pd.isna(row['release_year']): + doc['release_year'] = int(row['release_year']) + + # We store the text to encode along with doc to batch encode them + documents.append((doc, doc_text)) + + # Batch encode and insert + batch_size = 100 + for idx in range(0, len(documents), batch_size): + batch = documents[idx:idx + batch_size] + batch_docs = [item[0] for item in batch] + batch_texts = [item[1] for item in batch] + + # Encode the texts + embeddings = model.encode(batch_texts, normalize_embeddings=True) + + # Add embeddings to documents + for doc, emb in zip(batch_docs, embeddings): + doc['embedding'] = emb.tolist() + + # Import to Typesense + try: + client.collections['movies'].documents.import_(batch_docs, {'action': 'upsert'}) + print(f"Seeded {min(idx + batch_size, total_movies)} / {total_movies} movies...") + except Exception as e: + print(f"Error seeding batch starting at index {idx}: {e}") + + print("Data ingestion complete!") + +if __name__ == "__main__": + main() From d44b1b29bfca4d21ec70ffc5d69592deff9371c1 Mon Sep 17 00:00:00 2001 From: Nikhiladiga Date: Wed, 3 Jun 2026 09:47:00 +0530 Subject: [PATCH 15/15] First revision: add typesense-langchain-ai-search project to README --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index c521bd8..65a0116 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ code-samples/ ├── typesense-astro-search/ # Astro + Typesense search implementation ├── typesense-gin-full-text-search/ # Go (Gin) + Typesense backend implementation ├── typesense-kotlin/ # Kotlin (Android) + Typesense search implementation +├── typesense-langchain-ai-search/ # Python + LangChain + Typesense AI search implementation ├── typesense-next-search-bar/ # Next.js + Typesense search implementation ├── typesense-nuxt-search-bar/ # Nuxt.js + Typesense search implementation ├── typesense-qwik-js-search/ # Qwik + Typesense search implementation @@ -35,6 +36,7 @@ code-samples/ | [typesense-astro-search](./typesense-astro-search) | Astro | A modern search bar with instant search capabilities | | [typesense-gin-full-text-search](./typesense-gin-full-text-search) | Go (Gin) | Backend API with full-text search using Typesense | | [typesense-kotlin](./typesense-kotlin) | Kotlin (Android) | A native Android search bar with instant search capabilities | +| [typesense-langchain-ai-search](./typesense-langchain-ai-search) | LangChain (Python) | Conversational AI-powered movie search and recommendation app | | [typesense-next-search-bar](./typesense-next-search-bar) | Next.js | A modern search bar with instant search capabilities | | [typesense-nuxt-search-bar](./typesense-nuxt-search-bar) | Nuxt.js | A modern search bar with instant search capabilities | | [typesense-qwik-js-search](./typesense-qwik-js-search) | Qwik | Resumable search bar with real-time search and modern UI |