[GIS] Arcpy Spatial Join Fails: Field is Not Nullable

arcpyspatial-join

We are working to perform a spatial join of a very large point .shp of voters (target_features) with another of incidents (join_features).

arcpy.SpatialJoin_analysis(target_features, join_features, out_features, "JOIN_ONE_TO_MANY")

is working on a small subset of the voters, but when run on the entire set, the error is:

Field is not nullable

for each of the fields in the incidents .shp. Because this is Arc 10.2, we cannot AlterField_management or change the Nullability in Properties as seems possible in 10.3. Instead, we copied the .shp features to a Default.gbd Feature Class (which now claims to have nullable fields in Properties) and re-ran it, but received the same error.

Is there another way to change or ignore the nullability of fields?

Best Answer

You'll have to update the field mappings for your spatial join output. I'd iterate through fields and set those fields that are editable to nullable.

#target feature class
tFc = r"C:\temp\temp.gdb\target_featureclass"
#join feature class
jFc = r"C:\temp\temp.gdb\join_featureclass"


#list nullable fields for target feature class
tFields = [f.name for f in arcpy.ListFields (tFc)
           if f.type not in
           ["Geometry", "Guid", "OID", "Raster"]]

#list nullable fields for join feature class
jFields = [f.name for f in arcpy.ListFields (jFc)
           if f.type not in
           ["Geometry", "Guid", "OID", "Raster"]]


##target feature class
#create field mappings
fms = arcpy.FieldMappings ()
#iterate target fields
for field in arcpy.ListFields (tFc):
    #ignore shape/oid fields
    if field.type in ["Geometry", "OID"]:
        continue
    #create field map
    fm = arcpy.FieldMap ()
    #field name
    fieldName = field.name
    #add field to field map
    fm.addInputField (tFc, fieldName)
    #check if field name in nullable field list
    if fieldName in tFields:
        #set field to nullable
        field.isNullable = True
        #add output field to field map
        fm.outputField = field

    #add field map to field mappings
    fms.addFieldMap (fm)

##same for join feature class
for field in arcpy.ListFields (jFc):
    if field.type in ["Geometry", "OID"]:
        continue
    fm = arcpy.FieldMap ()
    fieldName = field.name
    fm.addInputField (jFc, fieldName)
    if fieldName in jFields:
        field.isNullable = True
        fm.outputField = field
    fms.addFieldMap (fm)

#perform spatial join with fieldmappings
arcpy.SpatialJoin_analysis(tFc, jFc, out_features, "JOIN_ONE_TO_MANY",
                           field_mapping = fms) 
Related Question