diff --git a/backend/app/api/search/nearby/route.ts b/backend/app/api/search/nearby/route.ts new file mode 100644 index 00000000..654753f2 --- /dev/null +++ b/backend/app/api/search/nearby/route.ts @@ -0,0 +1,40 @@ +import esClient from "lib/elasticsearch"; +import { NextResponse } from "next/server"; + +export async function POST(request: Request) { + const { lat, lon, distance = '20km' } = await request.json(); + + if (!lat || !lon) { + return NextResponse.json( + { error: 'Latitude and longitude are required' }, + { status: 400 } + ); + } + + const result = await esClient.search({ + index: 'pets', + query: { + bool: { + filter: [ + { + geo_distance: { + distance, + location: { lat, lon } + } + } + ] + } + }, + sort: [ + { + _geo_distance: { + location: { lat, lon }, + order: 'asc' + } + } + ] + }); + + return NextResponse.json(result.hits.hits); +} + diff --git a/backend/app/api/search/route.ts b/backend/app/api/search/route.ts new file mode 100644 index 00000000..5bfd4513 --- /dev/null +++ b/backend/app/api/search/route.ts @@ -0,0 +1,36 @@ +import esClient from 'lib/elasticsearch'; +import { NextResponse } from 'next/server'; + + +export async function GET(request: Request) { + const { searchParams } = new URL(request.url); + const query = searchParams.get('q'); + const breed = searchParams.get('breed'); + + const result = await esClient.search({ + index: 'pets', + query: { + bool: { + must: [ + { + multi_match: { + query: query ?? '', + fields: ['name^3', 'description', 'breed^2'], + fuzziness: 'AUTO' + } + } + ], + filter: breed + ? [{ term: { 'breed.keyword': breed } }] + : [] + } + }, + aggs: { + breed_facets: { + terms: { field: 'breed.keyword' } + } + } + }); + + return NextResponse.json(result.hits.hits); +} \ No newline at end of file diff --git a/backend/lib/elasticsearch.ts b/backend/lib/elasticsearch.ts new file mode 100644 index 00000000..a207830f --- /dev/null +++ b/backend/lib/elasticsearch.ts @@ -0,0 +1,8 @@ +import { Client } from '@elastic/elasticsearch'; + +const esClient = new Client({ + node: process.env.ELASTICSEARCH_URL, + auth: { apiKey: process.env.ELASTICSEARCH_API_KEY! } +}); + +export default esClient; \ No newline at end of file diff --git a/backend/package.json b/backend/package.json index 65783780..1001289b 100644 --- a/backend/package.json +++ b/backend/package.json @@ -138,4 +138,4 @@ "coverageDirectory": "../coverage", "testEnvironment": "node" } -} +} \ No newline at end of file