Why is my definition query having no effect?

09-29-2022 11:04 PM
New Contributor III

I'm trying to narrow down a layer using the lyr.definitionQuery = ... method, as below:

result = arcpy.mp.ConvertWebMapToArcGISProject(data, templateFull)
aprx = result.ArcGISProject
#get the map, layer, apply the definition query
m = aprx.listMaps()[0]
lyr = m.listLayers("MyLayer")[0]
lyr.definitionQuery = "GUIDId = '" + RequestedGUIDId + "'"

Now, this works fine if I do it using my current project on my computer, with everything loaded locally (so I don't have to bother with the ConvertWebMapToArcGISProject). However, we're trying to implement this online, so we have to get a json containing the layers we need and convert it to a project in the code.

Now, for some reason, the lyr.definitionQuery line is not working - or more rather, it's having no effect. No matter what, it always returns the same number of features, which is odd (as my layer contains about 20,000 features - yet it always returns 151, even if I enter different values, or even values that don't exist!).

The layer does support definition queries (I've tested that), and it definitely recalls the definition query (I've given it a delay after the definition query is set, and checked it by outputting). It's getting set, but for some reason the layer isn't paying any attention to it. 

0 Kudos
2 Replies
Occasional Contributor II

If the goal here is to apply a filter to a layer in a webmap in ArcGIS Online use the following.


from arcgis import GIS
from arcgis.mapping import WebMap

## connect to AGOL
agol = GIS("home")

## get the WebMap you want to update
wm_item = agol.content.get("WEBMAP_ITEM_ID")

## create WebMap object
webmap = WebMap(wm_item)

## get the layer of interest
lyr = webmap.get_layer(title="LAYER_NAME")

## the query to apply
def_qry = "GUIDId = '{0}'".format(RequestedGUIDId)

## set the filter definition
lyr.layerDefinition.definitionExpression = def_qry

## update the webmap



~ Mapping my way to retirement
New Contributor III

That's definitely some useful code. However, my code *was* working, but my code hadn't been put together well. I was trying to address a layer which didn't exist because I hadn't given it a title in the json I'm putting the webmap together with.

0 Kudos