0

I have a table with a field called 'keywords'. It is a JSONB field with an array of keyword metadata, including the keyword's name.

What I would like is to query the counts of all these keywords by name, i.e. aggregate on keyword name and count(id). All the examples of GROUP BY queries I can find just result in the grouping occuring on the full list (i.e. only giving me counts where the two records have the same set of keywords).

So is it possible to somehow expand the list of keywords in a way that lets me get these counts?

If not, I am still at the planning stage and could refactor my schema to better handle this.

  "keywords": [
    {
      "addedAt": "2017-04-07T21:11:00+0000",
      "addedBy": {
        "email": "[email protected]"
      },
      "keyword": {
        "name": "Animal"
      }
    },
    {
      "addedAt": "2017-04-07T20:54:00+0000",
      "addedBy": {
        "email": "[email protected]"
      },
      "keyword": {
        "name": "Mammal"
      }
    }
  ]

1 Answer 1

2

step-by-step demo:db<>fiddle

SELECT
    elems -> 'keyword' ->> 'name' AS keyword,             -- 2
    COUNT(*) AS count
FROM
    mytable t,
    jsonb_array_elements(myjson -> 'keywords') AS elems   -- 1
GROUP BY 1                                                -- 3
  1. Expand the array records into one row per element
  2. Get the keyword's names
  3. Group these text values.
Sign up to request clarification or add additional context in comments.

1 Comment

@deed02392 Did this help? In case, please do not forget to upvote and accept

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.