pythonr-tree

Python - Loading an R-Tree from file


I was able to successfully build an R-Tree spatial index and save it to a file.

from rtree import index

idx = index.Index("gridIndex")
idx.insert(..., ...)    
idx.insert(..., ...)
and so on...

Now I can load the saved index and use it:

idx = index.Index('gridIndex')
hits = idx.intersection([x, y], objects=True)

This works only if my index is in the same directory as my python file.

In my case, I'm running the main python file from a different directory:

python path/to/my_file/main.py

Now the index is not loaded, rather it creates an empty index in my working directory.

So how can I load my previously created index and specify its path?

I've tried to load it this way:

idx = index.Index(os.path.join(sys.path[0], 'gridIndex')) # doesn't work

And also this way:

idx = index.Index(os.path.join(sys.path[0], 'gridIndex.dat'))

Which creates a new empty index - two new files in the desired directory: gridIndex.dat.dat and gridIndex.dat.idx

In the documentation I found two methods - dumps() and loads(), but couldn't get it to work.


Solution

  • use the index.Rtree!

    something like this :

    from rtree import index
    
    idx = index.Rtree('path/to/gridIndex')
    hits = idx.intersection([x, y], objects=True)