简体   繁体   中英

Sequelize query string prefix / starts with

I'm building an autofill function that takes a string input and returns a list of string suggestions.

Sequelize's iLike:query returns every string in which the queried string appears. I would like to favour strings for which the query is a prefix. For example when query='sh' then the results should return strings that start with sh instead of having sh anywhere within the string.

This is relatively simple to do after receiving the data from the DB, however I was wondering if there is a way to accomplish this via sequelize while querying the DB? If so how?

The DB size will be between 10,000 and 100,000 strings of no more than a handful of words (company names to be exact).

Optional question: DB's usually have superior performance to generically written code, in this circumstance should there even be a noticeable difference? Or should I just collect all the data from the DB and apply some other filters on it after via vanilla JS.

let suggestions = yield db.Company.findAll({
  limit: 7,
    where: {
      company_name: {
        $iLike: '%'+this.data.query
      }
    }
 })

Seems like this is super easy! The '%' acts like a * from regex. So query + '%' returns any results where query is the prefix.

let suggestions = yield db.Company.findAll({
    limit: 5,
    where: { $or: [
      { stock_ticker: { $ilike: query + '%' } },
      { company_name: { $ilike: query + '%' } }
    ]},
    order: '"volume" DESC'
  })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM