0

lets say i have a column named keyword with values like ['wood', 'grass', 'tree', 'plant'], now how do I query that if this array contains wood or grass or both of them

my solution (here I am using a text string and searching through it)

  select * from table where keywords_column ~* 'wood';

but it is limited to one word only. It would be great if I would get solution in knex.js or Adonis Lucid

2
  • 1
    What is the data type? Commented May 25, 2022 at 10:05
  • This doesn't look like valid json Commented May 25, 2022 at 10:37

3 Answers 3

1

I thought this might work, but I didn't test it:

select * from table where keywords_column ~* 'wood' or keywords_column ~* 'grass';
Sign up to request clarification or add additional context in comments.

4 Comments

The any() operator only works with native arrays, not with JSON values containing arrays
I've used this method on fields of array type. Maybe he just needs an OR operation to search.
@a_horse_with_no_name You are right, I removed the wrong answer. Thank you for the correction
That would also find rows with grassland or woodpecker
0

You can use the contains operator ?|

select * 
from the_table 
where keywords_column ?| array['wood', 'grass'];

This assumes that keywords_columns is defined as jsonb (which it should be if you store JSON values). If it's not, you need to cast it keywords_column::jsonb

Online example

Comments

0

I would do like this:

SELECT * from table WHERE column SIMILAR TO '(wood |grass |tree |plant )%';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.