0

It is impossible to speed up the database due to indexing.

I create a table:

CREATE TABLE IF NOT EXISTS coordinate( Id serial primary key,
                                   Lat DECIMAL(9,6),
                                   Lon DECIMAL(9,6));

After that I add indexing:

CREATE INDEX indeLat ON coordinate(Lat);
CREATE INDEX indeLon ON coordinate(Lon);

Then the table is filled in:

INSERT INTO coordinate (Lat, Lon) VALUES(48.685444, 44.474254);

Fill in 100k random coordinates.

Now I need to return all coordinates that are included in a radius of N km from a given coordinate.

SELECT id, Lat, Lon
FROM coordinate
WHERE acos(sin(radians(48.704578))*sin(radians(Lat)) + cos(radians(48.704578))*cos(radians(Lat))*cos(radians(Lon)-radians(44.507112))) * 6371 < 50;

The test execution time is approximately 0.2 seconds, and if you do not do CREATE INDEX, the time does not change. I suspect that there is an error in the request, maybe you need to rebuild it somehow?

I'm sorry for my english

1 Answer 1

1

An index can only be used if the indexed expression is exactly what you have on the non-constant side of the operator. That is obviously not the case here.

For operations like this, you need to use the PostGIS extension. Then you can define a table like:

CREATE TABLE coordinate (
   id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
   p geography NOT NULL
);

and query like this:

SELECT id, p
FROM coordinate
WHERE ST_DWithin(p, 'POINT(48.704578 44.507112)'::geography, 50);

This index would speed up the query:

CREATE INDEX ON coordinate USING gist (p);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.