We all try to plan for the future when designing our data schema, but inevitably a new feature requires adding a column. The inverse can also be true: there is a column that you never use and it’s taking up space. Schema flexibility is a major differentiator between NoSQL databases, with some databases having a fixed schema and other databases allowing every record to have a different schema. GridDB sits somewhere in the middle, having a fixed schema that is easily altered.
For this post, we’re going to use the schema definition from our last blog post, Geospatial Analysis of NYC Crime Data with GridDB.
Viewing a Container’s Schema
Modifying the schema of a container requires you to fetch the ContainerInfo and ContainerColumnList objects which will then be modified and written back to the container. Thus, the place to start is displaying the ContainerColumnList.
ContainerInfo conInfo = store.getContainerInfo("COMPLAINTS"); ListnewColumnList = new ArrayList (); for ( int i = 0; i < conInfo.getColumnCount(); i++ ){ System.out.println(conInfo.getColumnInfo(i).getName()); }
Adding a Column
You can use any Java List method of adding a row. In this example, we append an Address to the schema. This is actually a real world example in schema modification: we were storing latitude and longitude in GridDB and after years of collecting data, we also wanted to store the GeoCoded information about that point.
ContainerInfo conInfo = store.getContainerInfo("COMPLAINTS"); ListnewColumnList = new ArrayList (); for ( int i = 0; i < conInfo.getColumnCount(); i++ ){ newColumnList.add(conInfo.getColumnInfo(i)); } newColumnList.add(new ColumnInfo("ADDRESS", GSType.STRING)); conInfo.setColumnInfoList(newColumnList); store.putCollection("COMPLAINTS", conInfo, true);
Removing a Column
Like adding data, the Java List API can be used to remove a ColumnInfo row from the Column List. Since we're making a copy of the data, the newColumnList can be altered during the copy as follows:
ContainerInfo conInfo = store.getContainerInfo("COMPLAINTS"); ListnewColumnList = new ArrayList (); for ( int i = 0; i < conInfo.getColumnCount(); i++ ){ if(!conInfo.getColumnInfo(i).getName().equals("VIC_AGE_GROUP")) newColumnList.add(conInfo.getColumnInfo(i)); } conInfo.setColumnInfoList(newColumnList); store.putCollection("COMPLAINTS", conInfo, true);
The entire Java program for the displaying, adding, and removing of columns can be downloaded here.
If you have any questions about the blog, please create a Stack Overflow post here https://stackoverflow.com/questions/ask?tags=griddb .
Make sure that you use the “griddb” tag so our engineers can quickly reply to your questions.