only-cliches / Nano-SQL

Universal database layer for the client, server & mobile devices. It's like Lego for databases.
https://nanosql.io
MIT License
782 stars 49 forks source link

How to create composite Index #181

Closed chitoadinugraha closed 5 years ago

chitoadinugraha commented 5 years ago

In the folowing example, how do I index state and city, so I can efficiently select

nSQL().query("select", [["address.city", "=", "a"], "AND", ["address.state", "=", "b"]]

model: { "id:uuid": {pk: true}, "age:float": {notNull: true}, "name:string[]": {default: []}, "properties:meta[]": {}, "address:obj": { model: { "street:string":{}, "city:string":{}, "zip:string":{}, "state:string":{} } }, "*:any": {} }

only-cliches commented 5 years ago

You can make a compound index like this:

{
    model: {
        "id:uuid": {pk: true},
        "age:float": {notNull: true},
        "name:string[]": {default: []},
        "properties:meta[]": {},
        "address:obj": {
            "model": {
                "street:string": {},
                "city:string": {},
                "zip:string": {},
                "state:string": {}
            }
        },
        "city_state:string": {default: ""}, // compound index column
        "*:any": {}
    },
    indexes: {
        "city_state:string":{ignore_case: true} // create compound index
    },
    fitler: (row) => {
        // runs every time a row is created or updated.
        return {
            ...row,
            city_state: row.city + row.state // update compound index on every upsert
        }
    }
} 

Then you can query like this:

nSQL("users").query("select").where(["city_state", "=", "TampaFlorida"]).exec().then..