# Search for keywords across posts

**URL:** https://meta.discourse.org/t/search-for-keywords-across-posts/134553
**Category:** Data & reporting
**Created:** [November 27, 2019, 12:26pm UTC](https://meta.discourse.org/t/search-for-keywords-across-posts/134553 "2019-11-27T12:26:46Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![david](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/david/32/157490_2.png) [@david](https://meta.discourse.org/u/david)
#### Post date: [November 27, 2019, 12:26pm UTC](https://meta.discourse.org/t/search-for-keywords-across-posts/134553/1 "2019-11-27T12:26:46Z")

</div>

This query will let you efficiently search for a keyword across all posts. It will be significantly faster than a `posts.raw LIKE` query, because it uses the postgres [full text search](https://www.postgresql.org/docs/9.5/textsearch.html) structured data

```sql
-- [params]
-- string :query

SELECT p.id as post_id FROM posts p
LEFT JOIN post_search_data psd ON psd.post_id = p.id
WHERE psd.search_data @@ TO_TSQUERY(:query)

```

---

<div class="post-metadata">

### Author: ![LotusJeff](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/lotusjeff/32/477888_2.png) [@LotusJeff](https://meta.discourse.org/u/LotusJeff)
#### Post date: [January 27, 2025, 3:08am UTC](https://meta.discourse.org/t/search-for-keywords-across-posts/134553/2 "2025-01-27T03:08:57Z")

</div>

What is missing in the fabulous code snippet is the ability to search by rank.

```plaintext
-- [params]
-- string :query

SELECT p.id as post_id, 
       ts_rank(psd.search_data, to_tsquery('english', :query)) AS rank
FROM posts p
LEFT JOIN post_search_data psd ON psd.post_id = p.id
WHERE psd.search_data @@ TO_TSQUERY(:query)
ORDER BY rank DESC

```
