Skip to content

Commit

Permalink
add note raw query for fts (#5750)
Browse files Browse the repository at this point in the history
  • Loading branch information
nikolasburk authored Mar 26, 2024
1 parent 49b9282 commit 42a49f1
Showing 1 changed file with 36 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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).
</TopBlock>

## Enabling full-text search
Expand Down Expand Up @@ -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);`
```

0 comments on commit 42a49f1

Please sign in to comment.