What to index on queries with lots of columns in the WHERE clause

后端 未结 2 1190
我寻月下人不归
我寻月下人不归 2020-12-31 16:52

Building a search engine for an apartment site and I\'m not sure how to index the apartments table.

Example of queries:

  • ...WHERE c
2条回答
  •  情话喂你
    2020-12-31 17:27

    You have to figure out what WHERE clauses you are going to use with this query, how often each will occur and and how selective each condition will be.

    • Don't index for queries that occur seldom unless you have to.

    • Use multicolumn indexes, starting with those columns that will occur in an = comparison.

    • Concerning the order of columns in a multicolumn index, start with those columns that will be used in a query by themselves (an index can be used for a query with only some of its columns, provided they are at the beginning of the index).

    • You might omit columns with low selectivity, like gender.

    For example, with your above queries, if they are all frequent and all columns are selective, these indexes would be good:

    ... ON apartments (city_id, rooms, size)
    
    ... ON apartments (area_id, ad_type, price)
    
    ... ON apartments (area_id, ad_type, published_at)
    

    These indexes could also be used for WHERE clauses with only area_id or city_id in them.

    It is bad to have too many indexes.

    If the above method would lead to too many indexes, e.g. because the user can pick arbitrary columns for the WHERE clause, it is better to index individual columns or occasionally pairs of columns that regularly go together.

    That way PostgreSQL can pick a bitmap index scan to combine several indexes for one query. That is less efficient than a regular index scan, but usually better than a sequential scan.

提交回复
热议问题