Similar to Indexing attribute field of shapefile in QGIS, I am wondering if such a thing like an attribute index exists for PyQGIS. Goal of its usage would be to iterate over two vector layers and find matching attribute values of a specified field in each layer. So it would work like a spatial index, just using attributes instead. So far I could only find, that I can create an Index using
createAttributeIndex() as stated here and here. But absolutely no further information about its usage, the way it works or examples.
Basically the idea is to speed up code written like this:
vectorlayer_a = QgsProject.instance().mapLayersByName("layer_a") vectorlayer_b = QgsProject.instance().mapLayersByName("layer_b") for feat_a in vectorlayer_a.getFeatures(): value_a = feat_a.attribute(1) for feat_b in vectorlayer_b.getFeatures(): value_b = feat_b.attribute(1) if value_a == value_b: print('Hurray, finally found (another) one. Can I find all of them faster with an attribute index?') # Do stuff some stuff like... geom_a = feat_a.geometry() geom_b = feat_b.geometry()
attribute(1) have any datatype or would such a thing only work with numerical values, if this 'thing' exists at all?