From 42a49f18d95f70b90b753e2354d5d0581302f0e6 Mon Sep 17 00:00:00 2001 From: Nikolas Date: Tue, 26 Mar 2024 09:21:29 +0100 Subject: [PATCH] add note raw query for fts (#5750) --- .../100-queries/060-full-text-search.mdx | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/content/200-orm/200-prisma-client/100-queries/060-full-text-search.mdx b/content/200-orm/200-prisma-client/100-queries/060-full-text-search.mdx index aafa8ecb7b..f25178bc34 100644 --- a/content/200-orm/200-prisma-client/100-queries/060-full-text-search.mdx +++ b/content/200-orm/200-prisma-client/100-queries/060-full-text-search.mdx @@ -9,6 +9,8 @@ preview: true Prisma Client supports full-text search for **PostgreSQL** databases in versions 2.30.0 and later, and **MySQL** databases in versions 3.8.0 and later. With full-text search enabled, you can add search functionality to your application by searching for text within a database column. +> **Note**: There currently is a [known issue](https://github.com/prisma/prisma/issues/8950) in the full-text search feature. If you observe slow search queries, you can [optimize your query with raw SQL](#full-text-search-with-raw-sql). + ## Enabling full-text search @@ -243,3 +245,37 @@ const result = await prisma.blogs.findMany({ ``` However, if you try to search on `title` alone, the search will fail with the error "Cannot find a fulltext index to use for the search" and the message code is `P2030`, because the index requires a search on both fields. + +## Full-text search with raw SQL + +Full-text search is currently in Preview and due to a [known issue](https://github.com/prisma/prisma/issues/8950), you may be seeing slow search queries. If that's the case, you can optimize your query using [raw SQL](/orm/prisma-client/queries/raw-database-access). + +### PostgreSQL + +In PostgreSQL, you can use `to_tsvector` and `to_tsquery` to express your search query: + +```ts +const term = `cat` +const result = + await prisma.$queryRaw`SELECT * FROM "Blog" WHERE to_tsvector('english', "Blog"."content") @@ to_tsquery('english', ${term});` +``` + +> **Note**: Depending on your language preferences, you may exchange `english` against another language in the SQL statement. + +If you want to include a wildcard in your search term, you can do this as follows: + +```ts +const term = `cat:*` +const result = + await prisma.$queryRaw`SELECT * FROM "Blog" WHERE to_tsvector('english', "Blog"."content") @@ to_tsquery('english', ${term});` +``` + +### MySQL + +In MySQL, you can express your search query as follows: + +```ts +const term = `cat` +const result = + await prisma.$queryRaw`SELECT * FROM Blog WHERE MATCH(content) AGAINST(${term} IN NATURAL LANGUAGE MODE);` +```