Reputation: 350
I am trying to create regex query to my PostgreSQL database. I have already done it, but the problem is that the query with regex is up to 3 times slower than the query where I search by the name. Is there any way to accelarate regex query or any other option to get results faster? I use django to create queries to the database.
My "normal" query where I search car by brand and model:
object_db = Car.objects.filter(brand='Ford', car_model='Focus-RS')
I create regex query like this:
object_db = Car.objects.filter(brand__regex=r'^Ford$', car_model__regex='^Focus[-_]*RS$')
My model:
class Car(models.Model):
car_data = models.ForeginKey(CarData, on_delete=models.CASCADE)
brand = models.CharField(max_length=100)
car_model = models.CharField(max_length=100)
class Meta:
index_together = (
('brand', 'car_model')
)
I get the result that I want but it take to much time to get it. How can I improve the speed of regex query or is there any other method for the same results?
Upvotes: 2
Views: 634
Reputation: 20702
You can use iexact
and combine queries using Q
:
object_db = Car.objects.filter(
brand__iexact="ford",
Q(car_model__iexact="focus-rs") | Q(car_model__iexact="focus_rs"))
This will match case-insensitive and perform an 'OR' query on the car_model
field.
Upvotes: 1