wikijs-fork/server/modules/search/postgres/engine.js

146 lines
4.9 KiB
JavaScript
Raw Normal View History

2019-03-09 05:51:02 +00:00
const _ = require('lodash')
2019-03-09 23:43:32 +00:00
const tsquery = require('pg-tsquery')()
2019-03-09 05:51:02 +00:00
module.exports = {
2019-03-09 23:43:32 +00:00
async activate() {
if (WIKI.config.db.type !== 'postgres') {
throw new WIKI.Error.SearchActivationFailed('Must use PostgreSQL database to activate this engine!')
}
2019-03-09 05:51:02 +00:00
},
2019-03-09 23:43:32 +00:00
async deactivate() {
2019-03-09 05:51:02 +00:00
// not used
},
/**
* INIT
*/
2019-03-09 23:43:32 +00:00
async init() {
2019-03-13 06:52:08 +00:00
WIKI.logger.info(`(SEARCH/POSTGRES) Initializing...`)
// -> Create Search Index
2019-03-09 23:43:32 +00:00
const indexExists = await WIKI.models.knex.schema.hasTable('pagesVector')
if (!indexExists) {
2019-03-13 06:52:08 +00:00
WIKI.logger.info(`(SEARCH/POSTGRES) Creating Pages Vector table...`)
2019-03-09 23:43:32 +00:00
await WIKI.models.knex.schema.createTable('pagesVector', table => {
table.increments()
table.string('path')
table.string('locale')
table.string('title')
table.string('description')
table.specificType('tokens', 'TSVECTOR')
2019-03-09 23:43:32 +00:00
})
}
// -> Create Words Index
const wordsExists = await WIKI.models.knex.schema.hasTable('pagesWords')
if (!wordsExists) {
2019-03-13 06:52:08 +00:00
WIKI.logger.info(`(SEARCH/POSTGRES) Creating Words Suggestion Index...`)
await WIKI.models.knex.raw(`
CREATE TABLE "pagesWords" AS SELECT word FROM ts_stat(
'SELECT to_tsvector(''simple'', pages."title") || to_tsvector(''simple'', pages."description") || to_tsvector(''simple'', pages."content") FROM pages WHERE pages."isPublished" AND NOT pages."isPrivate"'
)`)
await WIKI.models.knex.raw('CREATE EXTENSION IF NOT EXISTS pg_trgm')
await WIKI.models.knex.raw(`CREATE INDEX "pageWords_idx" ON "pagesWords" USING GIN (word gin_trgm_ops)`)
}
2019-03-13 06:52:08 +00:00
WIKI.logger.info(`(SEARCH/POSTGRES) Initialization completed.`)
2019-03-09 05:51:02 +00:00
},
/**
* QUERY
*
* @param {String} q Query
* @param {Object} opts Additional options
*/
async query(q, opts) {
2019-03-09 23:43:32 +00:00
try {
let suggestions = []
2019-03-09 23:43:32 +00:00
const results = await WIKI.models.knex.raw(`
SELECT id, path, locale, title, description
FROM "pagesVector", to_tsquery(?) query
WHERE query @@ "tokens"
ORDER BY ts_rank(tokens, query) DESC
2019-03-09 23:43:32 +00:00
`, [tsquery(q)])
if (results.rows.length < 5) {
const suggestResults = await WIKI.models.knex.raw(`SELECT word, word <-> ? AS rank FROM "pagesWords" WHERE similarity(word, ?) > 0.2 ORDER BY rank LIMIT 5;`, [q, q])
suggestions = suggestResults.rows.map(r => r.word)
}
2019-03-09 23:43:32 +00:00
return {
results: results.rows,
suggestions,
2019-03-09 23:43:32 +00:00
totalHits: results.rows.length
}
} catch (err) {
WIKI.logger.warn('Search Engine Error:')
WIKI.logger.warn(err)
}
2019-03-09 05:51:02 +00:00
},
/**
* CREATE
*
* @param {Object} page Page to create
*/
async created(page) {
2019-03-09 23:43:32 +00:00
await WIKI.models.knex.raw(`
INSERT INTO "pagesVector" (path, locale, title, description, tokens) VALUES (
'?', '?', '?', '?', (setweight(to_tsvector('${this.config.dictLanguage}', '?'), 'A') || setweight(to_tsvector('${this.config.dictLanguage}', '?'), 'B') || setweight(to_tsvector('${this.config.dictLanguage}', '?'), 'C'))
2019-03-09 23:43:32 +00:00
)
`, [page.path, page.localeCode, page.title, page.description, page.title, page.description, page.content])
2019-03-09 05:51:02 +00:00
},
/**
* UPDATE
*
* @param {Object} page Page to update
*/
async updated(page) {
2019-03-09 23:43:32 +00:00
await WIKI.models.knex.raw(`
UPDATE "pagesVector" SET
title = ?,
description = ?,
tokens = (setweight(to_tsvector('${this.config.dictLanguage}', ?), 'A') ||
setweight(to_tsvector('${this.config.dictLanguage}', ?), 'B') ||
setweight(to_tsvector('${this.config.dictLanguage}', ?), 'C'))
WHERE path = ? AND locale = ?
`, [page.title, page.description, page.title, page.description, page.content, page.path, page.localeCode])
2019-03-09 05:51:02 +00:00
},
/**
* DELETE
*
* @param {Object} page Page to delete
*/
async deleted(page) {
2019-03-09 23:43:32 +00:00
await WIKI.models.knex('pagesVector').where({
locale: page.localeCode,
2019-03-09 23:43:32 +00:00
path: page.path
}).del().limit(1)
2019-03-09 05:51:02 +00:00
},
/**
* RENAME
*
* @param {Object} page Page to rename
*/
async renamed(page) {
2019-03-09 23:43:32 +00:00
await WIKI.models.knex('pagesVector').where({
locale: page.localeCode,
2019-03-09 23:43:32 +00:00
path: page.sourcePath
}).update({
locale: page.localeCode,
2019-03-09 23:43:32 +00:00
path: page.destinationPath
})
2019-03-09 05:51:02 +00:00
},
/**
* REBUILD INDEX
*/
async rebuild() {
2019-03-13 06:52:08 +00:00
WIKI.logger.info(`(SEARCH/POSTGRES) Rebuilding Index...`)
2019-03-09 23:43:32 +00:00
await WIKI.models.knex('pagesVector').truncate()
await WIKI.models.knex.raw(`
INSERT INTO "pagesVector" (path, locale, title, description, "tokens")
SELECT path, "localeCode" AS locale, title, description,
(setweight(to_tsvector('${this.config.dictLanguage}', title), 'A') ||
setweight(to_tsvector('${this.config.dictLanguage}', description), 'B') ||
setweight(to_tsvector('${this.config.dictLanguage}', content), 'C')) AS tokens
2019-03-09 23:43:32 +00:00
FROM "pages"
WHERE pages."isPublished" AND NOT pages."isPrivate"`)
2019-03-13 06:52:08 +00:00
WIKI.logger.info(`(SEARCH/POSTGRES) Index rebuilt successfully.`)
2019-03-09 05:51:02 +00:00
}
}