5

I want to find the most common bi-grams (pair of words) in my table. How can I do this with BigQuery?

Felipe Hoffa
  • 54,922
  • 16
  • 151
  • 325

3 Answers3

11

BigQuery now supports SPLIT():

SELECT word, nextword, COUNT(*) c 
FROM (
SELECT pos, title, word, LEAD(word) OVER(PARTITION BY created_utc,title ORDER BY pos) nextword FROM (
SELECT created_utc, title, word, pos FROM FLATTEN(
  (SELECT created_utc, title, word, POSITION(word) pos FROM
   (SELECT created_utc, title, SPLIT(title, ' ') word FROM [bigquery-samples:reddit.full])
  ), word)
))
WHERE nextword IS NOT null
GROUP EACH BY 1, 2
ORDER BY c DESC
LIMIT 100
Felipe Hoffa
  • 54,922
  • 16
  • 151
  • 325
6

Now with a new function: ML.NGRAMS():

WITH data AS  (
  SELECT REGEXP_EXTRACT_ALL(LOWER(title), '[a-z]+') title_arr
  FROM `fh-bigquery.reddit_posts.2019_08`  
  WHERE title LIKE '% %'
  AND score>1
)


SELECT APPROX_TOP_COUNT(bigram, 10) top
FROM (
  SELECT ML.NGRAMS(title_arr, [2,2]) x
  FROM data
), UNNEST(x) bigram
WHERE LENGTH(bigram) > 10

enter image description here

Docs:

Felipe Hoffa
  • 54,922
  • 16
  • 151
  • 325
  • Thanks for sharing, @Felipe The statement that you provide is nested within a row. How would you "unnest" it further so that the only output columns are top.value and top.count and not the Row column? – Jordan Choo Jul 27 '21 at 00:38
1

The standard SQL version:

SELECT word, nextword, COUNT(*) c FROM (
SELECT pos, title, word, LEAD(word) OVER(PARTITION BY created_utc,title ORDER BY pos) nextword FROM (
SELECT created_utc, title, word, pos FROM ( 
    SELECT created_utc, title, SPLIT(title, ' ') word FROM `bigquery-samples.reddit.full`), UNNEST(word) as word WITH OFFSET pos))
WHERE nextword IS NOT null
GROUP BY 1, 2
ORDER BY c DESC
LIMIT 100

When unnesting an ARRAY you can retrieve the position of that element using the following syntax:

UNNEST(word) as word WITH OFFSET pos
LUIS PEREIRA
  • 478
  • 4
  • 20