# Improve Query performance

**URL:** <https://community.neo4j.com/t/improve-query-performance/69674>\
**Category:** Neo4j Graph Platform\
**Tags:** performance, cypher\
**Created:** [September 12, 2024, 6:49am UTC](https://community.neo4j.com/t/improve-query-performance/69674 "2024-09-12T06:49:21Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![sgs97](https://sea1.discourse-cdn.com/flex021/user_avatar/community.neo4j.com/sgs97/32/30124_2.png) [@sgs97](https://community.neo4j.com/u/sgs97)\
**Post date:** [September 12, 2024, 6:49am UTC](https://community.neo4j.com/t/improve-query-performance/69674/1 "2024-09-12T06:49:21Z")

</div>

Hi all,

I'm working on a query that involves a spatial search and filtering based on relationships between nodes. The goal is to find the nearest points of interest (POIs) within a certain distance and return their names, ordered by their distance and the number of repetitions.

Here’s the query I’m currently using:

```auto
MATCH (ca:Calle {cod:7})-[]-(i:Inmueble)
WITH ca, i AS inmuebles 
LIMIT 100
CALL spatial.withinDistance('Data.osm', inmuebles.punto, 5) 
YIELD node, distance
WITH node AS n, distance, ca
MATCH (c:OSMWay:Direccion)-[:GEOM]->(n)
WHERE c.name IS NOT NULL
WITH c, ca, distance 
ORDER BY distance ASC 
LIMIT 10
RETURN c.name, ca.nombre, COUNT(c.name) AS repeticiones 
ORDER BY repeticiones DESC 
LIMIT 1;

```

1. How can I improve the performance of this query, especially considering the use of `spatial.withinDistance` and the multiple `WITH` clauses?
2. Are there any indices or strategies that could help with optimizing spatial queries?
3. Should I consider restructuring the query for better readability and performance, or is there a more efficient way to achieve the same result?

---

<div class="post-metadata">

**Author:** ![glilienfield](https://sea1.discourse-cdn.com/flex021/user_avatar/community.neo4j.com/glilienfield/32/27534_2.png) [@glilienfield](https://community.neo4j.com/u/glilienfield)\
**Post date:** [September 12, 2024, 11:14am UTC](https://community.neo4j.com/t/improve-query-performance/69674/2 "2024-09-12T11:14:54Z")

</div>

You should have an index on property ‘cod’ for label ‘Calle’, so your initial match is fast.

Your query is not complicated beyond the use of the spatial library method to search for near by nodes.

You will call spatial.withinDistance up to 100 times. Is it possible to reduce that set first because some may be close to each other?

---

<div class="post-metadata">

**Author:** ![sgs97](https://sea1.discourse-cdn.com/flex021/user_avatar/community.neo4j.com/sgs97/32/30124_2.png) [@sgs97](https://community.neo4j.com/u/sgs97)\
**Post date:** [September 16, 2024, 8:37am UTC](https://community.neo4j.com/t/improve-query-performance/69674/3 "2024-09-16T08:37:07Z")

</div>

Thank you for answering my question. I've enhanced the query performance by reducing the maximum distance for the database search.
