Skip to content

Commit 48b9e67

Browse files
committed
simple template
Signed-off-by: Jason Chenyang Ji <chenyang.yale@gmail.com>
1 parent b674c54 commit 48b9e67

File tree

6 files changed

+89
-457
lines changed

6 files changed

+89
-457
lines changed

src/main/java/org/opensearch/plugin/insights/QueryInsightsPlugin.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,7 @@ public List<Setting<?>> getSettings() {
148148
QueryCategorizationSettings.SEARCH_QUERY_METRICS_ENABLED_SETTING,
149149
QueryInsightsSettings.TOP_N_EXPORTER_DELETE_AFTER,
150150
QueryInsightsSettings.TOP_N_EXPORTER_TYPE,
151-
QueryInsightsSettings.TOP_N_EXPORTER_TEMPLATE_ORDER,
151+
QueryInsightsSettings.TOP_N_EXPORTER_TEMPLATE_PRIORITY,
152152
QueryCategorizationSettings.SEARCH_QUERY_FIELD_TYPE_CACHE_SIZE_KEY
153153
);
154154
}

src/main/java/org/opensearch/plugin/insights/core/exporter/LocalIndexExporter.java

+20-250
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,8 @@ public class LocalIndexExporter implements QueryInsightsExporter {
7171
);
7272
private static final List<String> DEFAULT_SORTED_ORDERS = List.of("desc", "desc", "desc");
7373
private static final String TEMPLATE_NAME = "query_insights_override";
74-
private int templateOrder;
74+
private static final long DEFAULT_TEMPLATE_PRIORITY = 1000L;
75+
private long templatePriority;
7576

7677
/**
7778
* Constructor
@@ -95,7 +96,7 @@ public LocalIndexExporter(
9596
this.indexMapping = indexMapping;
9697
this.id = id;
9798
this.deleteAfter = DEFAULT_DELETE_AFTER_VALUE;
98-
this.templateOrder = QueryInsightsSettings.DEFAULT_TEMPLATE_ORDER;
99+
this.templatePriority = DEFAULT_TEMPLATE_PRIORITY;
99100
}
100101

101102
/**
@@ -144,23 +145,7 @@ public void export(final List<SearchQueryRecord> records) {
144145
try {
145146
final String indexName = buildLocalIndexName();
146147
if (!checkIndexExists(indexName)) {
147-
// Check for conflicting templates once and reuse results
148-
TemplateConflictInfo conflictInfo = findConflictingTemplatesWithDetails();
149-
if (!conflictInfo.getConflictingTemplates().isEmpty()) {
150-
logger.warn("Detected potentially conflicting templates: {}", conflictInfo.getConflictingTemplates());
151-
}
152-
153-
// Adjust the template order if needed based on conflict info
154-
if (conflictInfo.getHighestOrder() > 0) {
155-
int adjustedOrder = calculateAdjustedOrder(conflictInfo.getHighestOrder());
156-
if (adjustedOrder > templateOrder) {
157-
logger.debug("Adjusting template order from {} to {} due to conflicting templates",
158-
templateOrder, adjustedOrder);
159-
templateOrder = adjustedOrder;
160-
}
161-
}
162-
163-
// Create template with adjusted order
148+
// Create template with fixed priority
164149
ensureTemplateExists();
165150

166151
CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName);
@@ -202,15 +187,7 @@ public void onFailure(Exception e) {
202187
}
203188
} else {
204189
OperationalMetricsCounter.getInstance().incrementCounter(OperationalMetric.LOCAL_INDEX_EXPORTER_EXCEPTIONS);
205-
206-
// Use the conflict info we already have for error reporting
207-
if (cause.getMessage() != null && cause.getMessage().contains("index sort field")) {
208-
logger.error("Index creation failed due to sort field issue. This is likely caused by a conflicting template. " +
209-
"Detected templates: {}. Try increasing the template order value or removing conflicting templates.",
210-
conflictInfo.getConflictingTemplates(), cause);
211-
} else {
212-
logger.error("Unable to create query insights index: ", cause);
213-
}
190+
logger.error("Unable to create query insights index: ", cause);
214191
}
215192
}
216193
});
@@ -349,75 +326,12 @@ private Map<String, Object> readIndexMappingsAsMap() throws IOException {
349326
}
350327

351328
/**
352-
* Check if our template exists
353-
* @param templateName template name to check
354-
* @return true if template exists, false otherwise
355-
*/
356-
private boolean checkTemplateExists(String templateName) {
357-
try {
358-
ClusterState state = clusterService.state();
359-
return state.getMetadata().templates().containsKey(templateName);
360-
} catch (Exception e) {
361-
logger.error("Error checking template existence [{}]", templateName, e);
362-
return false;
363-
}
364-
}
365-
366-
/**
367-
* Ensure a template exists for our index pattern with a high priority
368-
* to override any wildcard templates
329+
* Ensure a template exists for our index pattern with the configured priority
369330
*/
370331
private void ensureTemplateExists() {
371332
String indexPattern = TOP_QUERIES_INDEX_PATTERN_GLOB;
372333

373-
// First check for any templates we need to compete with and adjust order if needed
374-
templateOrder = getAdjustedTemplateOrder();
375-
376334
try {
377-
boolean templateNeedsCreation = true;
378-
boolean templateNeedsUpdate = false;
379-
int existingPriority = -1;
380-
381-
// Check if our template exists in V2 templates
382-
ClusterState state = clusterService.state();
383-
if (state.getMetadata().templatesV2().containsKey(TEMPLATE_NAME)) {
384-
templateNeedsCreation = false;
385-
org.opensearch.cluster.metadata.ComposableIndexTemplate existingTemplate =
386-
state.getMetadata().templatesV2().get(TEMPLATE_NAME);
387-
388-
if (existingTemplate != null) {
389-
Integer currentPriority = existingTemplate.priority();
390-
existingPriority = currentPriority != null ? currentPriority : 0;
391-
if (existingPriority < templateOrder) {
392-
templateNeedsUpdate = true;
393-
logger.debug("Existing template [{}] priority {} needs to be updated to {}",
394-
TEMPLATE_NAME, existingPriority, templateOrder);
395-
}
396-
}
397-
} else {
398-
// Also check in V1 templates for backward compatibility
399-
if (state.getMetadata().templates().containsKey(TEMPLATE_NAME)) {
400-
// If a V1 template exists, we'll replace it with a V2 template
401-
templateNeedsCreation = false;
402-
templateNeedsUpdate = true;
403-
org.opensearch.cluster.metadata.IndexTemplateMetadata existingTemplate =
404-
state.getMetadata().templates().get(TEMPLATE_NAME);
405-
406-
if (existingTemplate != null) {
407-
Integer currentOrder = existingTemplate.order();
408-
existingPriority = currentOrder != null ? currentOrder : 0;
409-
logger.debug("Found old V1 template [{}] with order {}. Will replace with V2 template.",
410-
TEMPLATE_NAME, existingPriority);
411-
}
412-
}
413-
}
414-
415-
// Skip if template exists and doesn't need updating
416-
if (!templateNeedsCreation && !templateNeedsUpdate) {
417-
logger.debug("Template [{}] already exists with appropriate priority", TEMPLATE_NAME);
418-
return;
419-
}
420-
421335
// Create a V2 template (ComposableIndexTemplate)
422336
String mappingContent = readIndexMappings();
423337
org.opensearch.core.xcontent.XContentType xContentType = org.opensearch.core.xcontent.XContentType.JSON;
@@ -442,8 +356,8 @@ private void ensureTemplateExists() {
442356
Collections.singletonList(indexPattern),
443357
template,
444358
null, // No composed_of templates
445-
templateOrder, // Priority (using the same value as our adjusted order)
446-
templateOrder, // Version (using order as version for tracking changes)
359+
templatePriority, // Priority using configured value
360+
1L, // Version
447361
null, // No metadata
448362
null // No data stream
449363
);
@@ -460,18 +374,16 @@ private void ensureTemplateExists() {
460374
@Override
461375
public void onResponse(org.opensearch.action.support.AcknowledgedResponse response) {
462376
if (response.isAcknowledged()) {
463-
logger.info("Successfully {} V2 template [{}] with priority {}",
464-
templateNeedsCreation ? "created" : "updated", TEMPLATE_NAME, templateOrder);
377+
logger.info("Successfully created or updated V2 template [{}] with priority {}",
378+
TEMPLATE_NAME, templatePriority);
465379
} else {
466-
logger.warn("Failed to {} V2 template [{}]",
467-
templateNeedsCreation ? "create" : "update", TEMPLATE_NAME);
380+
logger.warn("Failed to create or update V2 template [{}]", TEMPLATE_NAME);
468381
}
469382
}
470383

471384
@Override
472385
public void onFailure(Exception e) {
473-
logger.error("Error {} V2 template [{}]",
474-
templateNeedsCreation ? "creating" : "updating", TEMPLATE_NAME, e);
386+
logger.error("Error creating or updating V2 template [{}]", TEMPLATE_NAME, e);
475387
OperationalMetricsCounter.getInstance().incrementCounter(OperationalMetric.LOCAL_INDEX_EXPORTER_EXCEPTIONS);
476388
}
477389
}
@@ -483,161 +395,19 @@ public void onFailure(Exception e) {
483395
}
484396

485397
/**
486-
* Find templates that might conflict with our index creation and collect information about them
487-
* @return TemplateConflictInfo containing conflicting templates and their highest order/priority
488-
*/
489-
private TemplateConflictInfo findConflictingTemplatesWithDetails() {
490-
List<String> conflictingTemplates = new ArrayList<>();
491-
int highestOrder = 0;
492-
493-
try {
494-
ClusterState state = clusterService.state();
495-
String ourIndexPattern = TOP_QUERIES_INDEX_PATTERN_GLOB;
496-
497-
// Find V1 templates that match our index pattern
498-
state.getMetadata().templates().forEach((name, template) -> {
499-
for (String pattern : template.patterns()) {
500-
// Check if this template would match our index pattern
501-
if (pattern.equals("*") || ourIndexPattern.matches(patternToRegex(pattern))) {
502-
// Only process templates not created by us
503-
if (!name.startsWith(TEMPLATE_NAME)) {
504-
Integer order = template.order();
505-
int orderValue = order != null ? order : 0;
506-
507-
// Track the highest order value
508-
if (orderValue > highestOrder) {
509-
highestOrder = orderValue;
510-
}
511-
512-
conflictingTemplates.add(name + " (V1, pattern: " + pattern + ", order: " +
513-
(order != null ? order : "default") + ")");
514-
}
515-
}
516-
}
517-
});
518-
519-
// Also check V2 templates (composable templates)
520-
state.getMetadata().templatesV2().forEach((name, template) -> {
521-
List<String> patterns = template.indexPatterns();
522-
for (String pattern : patterns) {
523-
// Check if this template would match our index pattern
524-
if (pattern.equals("*") || ourIndexPattern.matches(patternToRegex(pattern))) {
525-
// Only process templates not created by us
526-
if (!name.startsWith(TEMPLATE_NAME)) {
527-
// For V2 templates, priority is analogous to order in V1
528-
Integer priority = template.priority();
529-
int priorityValue = priority != null ? priority : 0;
530-
531-
// Track the highest priority value (to compare with V1 order)
532-
if (priorityValue > highestOrder) {
533-
highestOrder = priorityValue;
534-
}
535-
536-
conflictingTemplates.add(name + " (V2, pattern: " + pattern + ", priority: " +
537-
(priority != null ? priority : "default") + ")");
538-
}
539-
}
540-
}
541-
});
542-
} catch (Exception e) {
543-
logger.error("Error checking for conflicting templates", e);
544-
}
545-
546-
return new TemplateConflictInfo(conflictingTemplates, highestOrder);
547-
}
548-
549-
/**
550-
* Convert an index pattern to a regex for matching
551-
*/
552-
private String patternToRegex(String pattern) {
553-
return pattern
554-
.replace(".", "\\.")
555-
.replace("*", ".*")
556-
.replace("?", ".");
557-
}
558-
559-
/**
560-
* Find templates that might conflict with our index creation
561-
* @return List of potentially conflicting template names
562-
*/
563-
private List<String> findConflictingTemplates() {
564-
return findConflictingTemplatesWithDetails().getConflictingTemplates();
565-
}
566-
567-
/**
568-
* Ensure we're using a template order higher than any conflicting template
569-
* @return The adjusted template order
570-
*/
571-
private int getAdjustedTemplateOrder() {
572-
TemplateConflictInfo conflictInfo = findConflictingTemplatesWithDetails();
573-
return calculateAdjustedOrder(conflictInfo.getHighestOrder());
574-
}
575-
576-
/**
577-
* Calculate the adjusted order value based on a conflicting order
578-
* @param highestConflictingOrder The highest order value found in conflicting templates
579-
* @return The adjusted order value
580-
*/
581-
private int calculateAdjustedOrder(int highestConflictingOrder) {
582-
// If no conflicts, return the current order
583-
if (highestConflictingOrder <= 0) {
584-
return templateOrder;
585-
}
586-
587-
// Add a buffer to ensure we're substantially higher
588-
int adjustedOrder = highestConflictingOrder + 100;
589-
590-
// If template order gets too high, we might approach Integer.MAX_VALUE
591-
// In that case, use a very high value but leave room for future conflicts
592-
if (adjustedOrder > Integer.MAX_VALUE - 1000) {
593-
adjustedOrder = Integer.MAX_VALUE - 1000;
594-
}
595-
596-
// Only log if we're actually changing the order
597-
if (adjustedOrder > templateOrder) {
598-
logger.debug("Adjusting template order from {} to {} due to conflicting templates with highest order/priority {}",
599-
templateOrder, adjustedOrder, highestConflictingOrder);
600-
return adjustedOrder;
601-
}
602-
603-
return templateOrder;
604-
}
605-
606-
/**
607-
* Value class to hold information about conflicting templates
608-
*/
609-
private static class TemplateConflictInfo {
610-
private final List<String> conflictingTemplates;
611-
private final int highestOrder;
612-
613-
TemplateConflictInfo(List<String> conflictingTemplates, int highestOrder) {
614-
this.conflictingTemplates = conflictingTemplates;
615-
this.highestOrder = highestOrder;
616-
}
617-
618-
List<String> getConflictingTemplates() {
619-
return conflictingTemplates;
620-
}
621-
622-
int getHighestOrder() {
623-
return highestOrder;
624-
}
625-
}
626-
627-
/**
628-
* Set the template order for the exporter
629-
* @param templateOrder New template order value
398+
* Set the template priority for the exporter
399+
* @param templatePriority New template priority value
630400
*/
631-
public void setTemplateOrder(final int templateOrder) {
632-
this.templateOrder = templateOrder;
401+
public void setTemplatePriority(final long templatePriority) {
402+
this.templatePriority = templatePriority;
633403
}
634404

635405
/**
636-
* Get the current template order
637-
* @return Current template order value
406+
* Get the current template priority
407+
* @return Current template priority value
638408
*/
639-
public int getTemplateOrder() {
640-
return templateOrder;
409+
public long getTemplatePriority() {
410+
return templatePriority;
641411
}
642412

643413
}

0 commit comments

Comments
 (0)