+ FOR term IN SELECT unnest(string_to_array(unnest(lookup_terms), ' ')) LOOP
+ term := trim(term);
+ IF NOT (ARRAY[term] <@ partial_terms) THEN
+ partial_terms := partial_terms || term;
+ END IF;
+ END LOOP;
+
+ partial_tokens := '{}'::INT[];
+ FOR term IN SELECT unnest(partial_terms) LOOP
+ SELECT min(word_id), max(info->>'count') INTO term_id, term_count
+ FROM word WHERE word_token = term and type = 'w';
+
+ IF term_id IS NULL THEN
+ term_id := nextval('seq_word');
+ term_count := 0;
+ INSERT INTO word (word_id, word_token, info)
+ VALUES (term_id, term, json_build_object('count', term_count));
+ END IF;
+
+ IF term_count < {{ max_word_freq }} THEN
+ partial_tokens := array_merge(partial_tokens, ARRAY[term_id]);
+ END IF;
+ END LOOP;