001/* 002 * Copyright 2026 Anyware Services 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.ametys.plugins.ai.search; 017 018import java.util.List; 019import java.util.Map; 020import java.util.Objects; 021import java.util.Optional; 022 023import org.ametys.cms.search.query.Query; 024import org.ametys.cms.search.query.QuerySyntaxException; 025 026/** 027 * An embedding-based query, which can be used to perform a vector search (solr knn query). 028 */ 029public class VectorQuery implements Query 030{ 031 private String _fieldName; 032 private double _minReturn; 033 private List<Float> _vector; 034 035 /** 036 * Create a vector query with the given field name and vector, and a default of minReturn of 0.7. 037 * @param fieldName the name of the field to search on 038 * @param vector the vector to search with 039 */ 040 public VectorQuery(String fieldName, List<Float> vector) 041 { 042 this(fieldName, vector, 0.7); 043 } 044 045 /** 046 * Create a vector query with the given field name and vector, and a default topK of 10. 047 * @param fieldName the name of the field to search on 048 * @param vector the vector to search with 049 * @param minReturn the min return value for the vector similarity query (between 0 and 1, default is 0.7) 050 */ 051 public VectorQuery(String fieldName, List<Float> vector, double minReturn) 052 { 053 _fieldName = fieldName; 054 _vector = vector; 055 _minReturn = minReturn; 056 } 057 058 public String build() throws QuerySyntaxException 059 { 060 return "{!vectorSimilarity f=" + _fieldName + " minReturn=" + _minReturn + " }" + _vector.toString(); 061 } 062 063 public Optional<Object> buildAsJson() throws QuerySyntaxException 064 { 065 return Optional.of(Map.of( 066 "vectorSimilarity", Map.of( 067 "f", _fieldName, 068 "minReturn", _minReturn, 069 "query", _vector.toString() 070 ) 071 )); 072 } 073 074 @Override 075 public int hashCode() 076 { 077 return Objects.hash(_fieldName, _vector, _minReturn); 078 } 079 080 @Override 081 public boolean equals(Object obj) 082 { 083 if (this == obj) 084 { 085 return true; 086 } 087 088 if (obj == null || getClass() != obj.getClass()) 089 { 090 return false; 091 } 092 093 VectorQuery other = (VectorQuery) obj; 094 return Objects.equals(_fieldName, other._fieldName) 095 && Objects.equals(_vector, other._vector) 096 && Objects.equals(_minReturn, other._minReturn); 097 } 098}