-
Notifications
You must be signed in to change notification settings - Fork 40
Elasticsearch implementation for Beneficiary Search #123
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
vanitha1822
wants to merge
14
commits into
release-3.6.1
Choose a base branch
from
nd/vs/AMM-1951
base: release-3.6.1
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+5,840
β1,758
Open
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
2cf9083
fix: ES Implementation-mapping, indexing and async records
vanitha1822 47aab37
fix: add service for ES Search
vanitha1822 96e52ae
fix: search implementation
vanitha1822 b6bec79
fix: add additional fields as per the requirement
vanitha1822 258a5ee
fix: comment extra fields
vanitha1822 2944857
fix: rename the files, remove commented code
vanitha1822 580b55e
fix: update pom.xml
vanitha1822 bcdf730
fix: revert advancesearch
vanitha1822 3b17ee7
fix: add properties
vanitha1822 c9add66
fix: resolve conflicts
vanitha1822 5d62953
fix: coderabbit comments
vanitha1822 5b5c3a1
fix: remove comment code
vanitha1822 b8e8682
fix: accept numeric values for search
vanitha1822 ff4f1bc
fix: update the env variable
vanitha1822 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
70 changes: 70 additions & 0 deletions
70
src/main/java/com/iemr/common/identity/ScheduledSyncJob.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,70 @@ | ||
| package com.iemr.common.identity; | ||
|
|
||
| import org.slf4j.Logger; | ||
| import org.slf4j.LoggerFactory; | ||
| import org.springframework.beans.factory.annotation.Autowired; | ||
| import org.springframework.beans.factory.annotation.Value; | ||
| import org.springframework.scheduling.annotation.Scheduled; | ||
| import org.springframework.stereotype.Component; | ||
|
|
||
| import com.iemr.common.identity.data.elasticsearch.ElasticsearchSyncJob; | ||
| import com.iemr.common.identity.service.elasticsearch.SyncJobService; | ||
|
|
||
| /** | ||
| * Scheduled jobs for Elasticsearch sync | ||
| * | ||
| * To enable scheduled sync, set: elasticsearch.sync.scheduled.enabled=true in | ||
| * application.properties | ||
| */ | ||
| @Component | ||
| public class ScheduledSyncJob { | ||
|
|
||
| private static final Logger logger = LoggerFactory.getLogger(ScheduledSyncJob.class); | ||
|
|
||
| @Autowired | ||
| private SyncJobService syncJobService; | ||
|
|
||
| @Value("${elasticsearch.sync.scheduled.enabled:true}") | ||
| private boolean scheduledSyncEnabled; | ||
|
|
||
| /** | ||
| * Run full sync every day at 2 AM Cron: second, minute, hour, day, month, | ||
| * weekday | ||
| */ | ||
| @Scheduled(cron = "${elasticsearch.sync.scheduled.cron:0 0 2 * * ?}") | ||
| public void scheduledFullSync() { | ||
| if (!scheduledSyncEnabled) { | ||
| logger.debug("Scheduled sync is disabled"); | ||
| return; | ||
| } | ||
|
|
||
| logger.info("Starting scheduled full sync job"); | ||
| try { | ||
| // Check if there's already a sync running | ||
| if (syncJobService.isFullSyncRunning()) { | ||
| logger.warn("Full sync already running. Skipping scheduled sync."); | ||
| return; | ||
| } | ||
|
|
||
| // Start async sync | ||
| ElasticsearchSyncJob job = syncJobService.startFullSyncJob("SCHEDULER"); | ||
| logger.info("Scheduled sync job started: jobId={}", job.getJobId()); | ||
|
|
||
| } catch (Exception e) { | ||
| logger.error("Error starting scheduled sync: {}", e.getMessage(), e); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Clean up old completed jobs (keep last 30 days) Runs every Sunday at 3 AM | ||
| */ | ||
| @Scheduled(cron = "0 0 3 * * SUN") | ||
| public void cleanupOldJobs() { | ||
| if (!scheduledSyncEnabled) { | ||
| return; | ||
| } | ||
|
|
||
| logger.info("Running cleanup of old sync jobs..."); | ||
|
|
||
| } | ||
| } |
100 changes: 100 additions & 0 deletions
100
src/main/java/com/iemr/common/identity/config/ElasticsearchConfig.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,100 @@ | ||
| package com.iemr.common.identity.config; | ||
|
|
||
| import java.io.IOException; | ||
|
|
||
| import co.elastic.clients.elasticsearch.ElasticsearchClient; | ||
| import co.elastic.clients.json.jackson.JacksonJsonpMapper; | ||
| import co.elastic.clients.transport.ElasticsearchTransport; | ||
| import co.elastic.clients.transport.rest_client.RestClientTransport; | ||
| import org.slf4j.Logger; | ||
| import org.slf4j.LoggerFactory; | ||
|
|
||
| import org.apache.http.HttpHost; | ||
| import org.apache.http.auth.AuthScope; | ||
| import org.apache.http.auth.UsernamePasswordCredentials; | ||
| import org.apache.http.impl.client.BasicCredentialsProvider; | ||
| import org.elasticsearch.client.RestClient; | ||
| import org.springframework.beans.factory.annotation.Value; | ||
| import org.springframework.context.annotation.Bean; | ||
| import org.springframework.context.annotation.Configuration; | ||
|
|
||
| @Configuration | ||
| public class ElasticsearchConfig { | ||
|
|
||
| private static final Logger logger = LoggerFactory.getLogger(ElasticsearchConfig.class); | ||
|
|
||
| @Value("${elasticsearch.host}") | ||
| private String esHost; | ||
|
|
||
| @Value("${elasticsearch.port}") | ||
| private int esPort; | ||
|
|
||
| @Value("${elasticsearch.username}") | ||
| private String esUsername; | ||
|
|
||
| @Value("${elasticsearch.password}") | ||
| private String esPassword; | ||
|
|
||
| @Value("${elasticsearch.index.beneficiary}") | ||
| private String indexName; | ||
|
|
||
| @Bean | ||
| public ElasticsearchClient elasticsearchClient() { | ||
| BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); | ||
| credentialsProvider.setCredentials( | ||
| AuthScope.ANY, | ||
| new UsernamePasswordCredentials(esUsername, esPassword) | ||
| ); | ||
|
|
||
| RestClient restClient = RestClient.builder( | ||
| new HttpHost(esHost, esPort, "http") | ||
| ).setHttpClientConfigCallback(httpClientBuilder -> | ||
| httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider) | ||
| ).build(); | ||
|
|
||
| ElasticsearchTransport transport = new RestClientTransport( | ||
| restClient, | ||
| new JacksonJsonpMapper() | ||
| ); | ||
|
|
||
| return new ElasticsearchClient(transport); | ||
| } | ||
|
|
||
| @Bean | ||
| public Boolean createIndexMapping(ElasticsearchClient client) throws IOException { | ||
|
|
||
| // Check if index exists | ||
| boolean exists = client.indices().exists(e -> e.index(indexName)).value(); | ||
|
|
||
| if (!exists) { | ||
| client.indices().create(c -> c | ||
| .index(indexName) | ||
| .mappings(m -> m | ||
| .properties("beneficiaryRegID", p -> p.keyword(k -> k)) | ||
| .properties("firstName", p -> p.text(t -> t | ||
| .fields("keyword", f -> f.keyword(k -> k)) | ||
| .analyzer("standard") | ||
| )) | ||
| .properties("lastName", p -> p.text(t -> t | ||
| .fields("keyword", f -> f.keyword(k -> k)) | ||
| .analyzer("standard") | ||
| )) | ||
| .properties("phoneNum", p -> p.keyword(k -> k)) | ||
| .properties("fatherName", p -> p.text(t -> t.analyzer("standard"))) | ||
| .properties("spouseName", p -> p.text(t -> t.analyzer("standard"))) | ||
| .properties("aadharNo", p -> p.keyword(k -> k)) | ||
| .properties("govtIdentityNo", p -> p.keyword(k -> k)) | ||
| ) | ||
| .settings(s -> s | ||
| .numberOfShards("3") | ||
| .numberOfReplicas("1") | ||
| .refreshInterval(t -> t.time("1s")) | ||
| ) | ||
| ); | ||
|
|
||
| logger.info("Created Elasticsearch index with proper mappings"); | ||
| } | ||
| return true; | ||
|
|
||
| } | ||
| } |
56 changes: 56 additions & 0 deletions
56
src/main/java/com/iemr/common/identity/config/ElasticsearchSyncConfig.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,56 @@ | ||
| package com.iemr.common.identity.config; | ||
|
|
||
| import java.util.concurrent.Executor; | ||
|
|
||
| import org.springframework.context.annotation.Bean; | ||
| import org.springframework.context.annotation.Configuration; | ||
| import org.springframework.scheduling.annotation.EnableAsync; | ||
| import org.springframework.scheduling.annotation.EnableScheduling; | ||
| import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; | ||
|
|
||
| /** | ||
| * Configuration for async processing and scheduling | ||
| */ | ||
| @Configuration | ||
| @EnableAsync | ||
| @EnableScheduling | ||
| public class ElasticsearchSyncConfig { | ||
|
|
||
| /** | ||
| * Thread pool for Elasticsearch sync operations | ||
| * Configured for long-running background jobs | ||
| */ | ||
| @Bean(name = "elasticsearchSyncExecutor") | ||
| public Executor elasticsearchSyncExecutor() { | ||
| ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); | ||
|
|
||
| // Only 1-2 sync jobs should run at a time to avoid overwhelming DB/ES | ||
| executor.setCorePoolSize(5); | ||
| executor.setMaxPoolSize(10); | ||
| executor.setQueueCapacity(100); | ||
| executor.setThreadNamePrefix("es-sync-"); | ||
| executor.setKeepAliveSeconds(60); | ||
|
|
||
| // Handle rejected tasks | ||
| executor.setRejectedExecutionHandler((r, executor1) -> { | ||
| throw new RuntimeException("Elasticsearch sync queue is full. Please wait for current job to complete."); | ||
| }); | ||
|
|
||
| executor.initialize(); | ||
| return executor; | ||
| } | ||
|
|
||
| /** | ||
| * General purpose async executor | ||
| */ | ||
| @Bean(name = "taskExecutor") | ||
| public Executor taskExecutor() { | ||
| ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); | ||
| executor.setCorePoolSize(5); | ||
| executor.setMaxPoolSize(10); | ||
| executor.setQueueCapacity(100); | ||
| executor.setThreadNamePrefix("async-"); | ||
| executor.initialize(); | ||
| return executor; | ||
| } | ||
| } |
69 changes: 69 additions & 0 deletions
69
src/main/java/com/iemr/common/identity/controller/IdentityESController.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| package com.iemr.common.identity.controller; | ||
|
|
||
|
|
||
| import java.util.HashMap; | ||
| import java.util.*; | ||
|
|
||
| import org.slf4j.Logger; | ||
| import org.slf4j.LoggerFactory; | ||
| import org.springframework.beans.factory.annotation.Autowired; | ||
| import org.springframework.http.ResponseEntity; | ||
| import org.springframework.web.bind.annotation.*; | ||
| import com.iemr.common.identity.service.elasticsearch.ElasticsearchService; | ||
| import com.iemr.common.identity.utils.CookieUtil; | ||
| import com.iemr.common.identity.utils.JwtUtil; | ||
|
|
||
| import jakarta.servlet.http.HttpServletRequest; | ||
|
|
||
| /** | ||
| * Elasticsearch-enabled Beneficiary Search Controller | ||
| * All search endpoints with ES support | ||
| */ | ||
| @RestController | ||
| @RequestMapping("/beneficiary") | ||
| public class IdentityESController { | ||
|
|
||
| private static final Logger logger = LoggerFactory.getLogger(IdentityESController.class); | ||
|
|
||
| @Autowired | ||
| private ElasticsearchService elasticsearchService; | ||
|
|
||
| @Autowired | ||
| private JwtUtil jwtUtil; | ||
|
|
||
| /** | ||
| * MAIN UNIVERSAL SEARCH ENDPOINT | ||
| * Searches across all fields - name, phone, ID, etc. | ||
| * | ||
| * Usage: GET /beneficiary/search?query=vani | ||
| * Usage: GET /beneficiary/search?query=9876543210 | ||
| */ | ||
| @GetMapping("/search") | ||
| public ResponseEntity<Map<String, Object>> search(@RequestParam String query, HttpServletRequest request) { | ||
| try { | ||
| String jwtToken = CookieUtil.getJwtTokenFromCookie(request); | ||
| String userId = jwtUtil.getUserIdFromToken(jwtToken); | ||
| int userID=Integer.parseInt(userId); | ||
| List<Map<String, Object>> results = elasticsearchService.universalSearch(query, userID); | ||
|
|
||
| Map<String, Object> response = new HashMap<>(); | ||
| response.put("data", results); | ||
| response.put("statusCode", 200); | ||
| response.put("errorMessage", "Success"); | ||
| response.put("status", "Success"); | ||
|
|
||
| return ResponseEntity.ok(response); | ||
|
|
||
| } catch (Exception e) { | ||
| Map<String, Object> errorResponse = new HashMap<>(); | ||
| errorResponse.put("data", new ArrayList<>()); | ||
| errorResponse.put("statusCode", 500); | ||
| errorResponse.put("errorMessage", e.getMessage()); | ||
| errorResponse.put("status", "Error"); | ||
|
|
||
| return ResponseEntity.status(500).body(errorResponse); | ||
| } | ||
| } | ||
|
|
||
|
|
||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.