Ambiguous search LIKE statements do not hit

Asked 2 years ago, Updated 2 years ago, 138 views

I used the postgreSQL LIKE statement in the ORM called gorm in the Go language, but somehow I can't get the data.

The model is assumed to be:

 type Model structure {
    ID int
    Name string     
    Phonetic string // Name hiragana
}

I would like to get something that starts with a line of Phonetic here, so I will issue the following SQL.
db.Where("phonetic LIKE?", "[Ahhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh]%").Find(&models)

However, there are some data that start with a line of Phonetic (for example, "orora") but it cannot be retrieved.What kind of SQL should I issue to get it?

go sql postgresql gorm

2022-09-30 19:00

1 Answers

The LIKE operator is a very simple pattern match, not a regular expression match: https://www.postgresql.org/docs/current/functions-matching.html

You can use PostgreSQL to match using regular expressions with ~ operators, like phonetic~'^[Ahhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh

However, matches using regular expressions have disadvantages such as difficulty in using indexes, and query execution tends to take longer as the number of records increases.If you are having trouble with running time, you may want to create a column to use only the first character, or if there are various search patterns, consider using a full-text search engine.


2022-09-30 19:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.