3

I need to filter records by how many words exist in a certain column.

the following works, but of course returns a character count...I need a word count

 Flight.where("length(route) > 3")

Is there a rails way (or any way) to do this?

This is getting closer (its right out of the rails docs) but results in error

 Flight.where("array_length(route, 1) >= 3")

 ERROR: aggregate functions are not allowed in WHERE
 ERROR:  function array_length(character varying, integer) does not exist

Docs also suggest using HAVING .. also not working

Flight.having("route.count > ?", 2)

3 Answers 3

3

Flight.where("array_length(route, 1) >= 3") does work, but the column must be set as type array.

see this post for more Rails Migration changing column to use Postgres arrays

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect answer for newer versions of PSQL when array columns are introduced.. Instead of manipulating array in memory, let Db server handle it.
1

You can use split to create an array from a string with words spaced by whitespace within the string and count the total.

Flight.select(:route).select { |flight| flight.route.split(" ").length > 3 }

1 Comment

Data type array didnt work for me after all. I reverted back to basic string type column. This is the best answer so far.
0

Assuming you want quite a naïve definition of "word" as "things with spaces in between", split the string and get the length of the resulting array.

In plain SQL, that'd be:

SELECT array_length(string_to_array(route, ' '), 1);

e.g.

SELECT array_length(string_to_array('this is - five, words', ' '), 1);

If you want to get fancier and ignore punctuation etc, use regexp_split_to_array. You can also look at using to_tsvector to create a stemmed and de-duplicated form if desired.

1 Comment

Thanks for answer. I'm using ActiveRecord. Postgres offers an array column type that, if set up correctly, provides Flight.where("array_length(route, 1) >= 3"). I didnt know I needed the column to be of type array in order for that to work.

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.