how to read all date from PostgreSQL with array field jpa/hibernate ejb - arrays

i had problem to read all date from db PostgreSQL and jpa/hibernate ejb
my table has array field see below :
#Entity
public class MyTable{
private Long id;
private String name;
private String[] values;
#Type(type = "com.usertype.StringArrayUserType")
public String[] getValues(){
return values;
}
public void setValues(String[] values){
this.values = values;
}
}
and user type class like this :
package com.almasprocess.model.bl.en;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.usertype.UserType;
import java.io.Serializable;
import java.sql.*;
public class StringArrayUserType implements UserType {
protected static final int[] SQL_TYPES = { Types.ARRAY };
#Override
public Object assemble(Serializable cached, Object owner) throws HibernateException {
return this.deepCopy(cached);
}
#Override
public Object deepCopy(Object value) throws HibernateException {
return value;
}
#Override
public Serializable disassemble(Object value) throws HibernateException {
return (String[]) this.deepCopy(value);
}
#Override
public boolean equals(Object x, Object y) throws HibernateException {
if (x == null) {
return y == null;
}
return x.equals(y);
}
#Override
public int hashCode(Object x) throws HibernateException {
return x.hashCode();
}
#Override
public boolean isMutable() {
return true;
}
#Override
public Object nullSafeGet(ResultSet resultSet, String[] names, SessionImplementor session, Object owner)
throws HibernateException, SQLException {
if (resultSet.wasNull()) {
return null;
}
if(resultSet.getArray(names[0]) == null){
return new Integer[0];
}
Array array = resultSet.getArray(names[0]);
String[] javaArray = (String[]) array.getArray();
return javaArray;
}
#Override
public void nullSafeSet(PreparedStatement statement, Object value, int index, SessionImplementor session)
throws HibernateException, SQLException {
Connection connection = statement.getConnection();
if (value == null) {
statement.setNull(index, SQL_TYPES[0]);
} else {
String[] castObject = (String[]) value;
Array array = connection.createArrayOf("varchar", castObject);
statement.setArray(index, array);
}
}
#Override
public Object replace(Object original, Object target, Object owner) throws HibernateException {
return original;
}
#Override
public Class<String[]> returnedClass() {
return String[].class;
}
#Override
public int[] sqlTypes() {
return new int[] { Types.ARRAY };
}
}
and read date like this in ejb class :
public List readMailBank(){
String query = "select mt from mytable mt";
TypedQuery<StringArrayUserType> typedQuery = em.createQuery(query , StringArrayUserType.class);
List<StringArrayUserType> results = typedQuery.getResultList();
return results;
}
or like this sample code :
public List readMailBank(){
Type stringType = (Type) new TypeLocatorImpl(new TypeResolver()).custom(StringArrayUserType.class);
Query query = em.createNativeQuery("select mt from mytable mt");
query.unwrap(SQLQuery.class).addScalar("mb", (org.hibernate.type.Type) stringType);
List<Mailbank>results = query.getResultList();
return results;
}
but i had this error :
Caused by: java.lang.IllegalArgumentException: Type specified for TypedQuery [com.usertype.StringArrayUserType] is incompatible with query return type [class [Ljava.lang.String;]
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.resultClassChecking(AbstractEntityManagerImpl.java:387) [hibernate-entitymanager-4.3.7.Final.jar:4.3.7.Final]
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:344) [hibernate-entitymanager-4.3.7.Final.jar:4.3.7.Final]
at org.jboss.as.jpa.container.AbstractEntityManager.createQuery(AbstractEntityManager.java:131) [wildfly-jpa-8.2.0.Final.jar:8.2.0.Final]
please help me to read all data from db and fills array in to my array field?
thanks

I think the problem with your first example is that you try to create your query for values in Java which is a String[], but your JPQL asks for MyTable values. Which classes are not extending each other, thus you get an exception about the type incompatibility.
Something like
select mt.values from mytable mt
should give you what you want. (If it doesn't work at once, here is some documentation about selecting values instead of entities.)

Related

Using an Enum in #BeanParam

I am using a #BeanParam like this:
#GET
public Response listAllPaged(#BeanParam PagedRequest pagedRequest) {
// Do stuff...
}
The bean itself:
public class PagedRequest {
#QueryParam("sortOrder")
#DefaultValue("0")
public int sortOrder;
}
Now I would like to change the type of sortOrder to the following enum:
public enum SortOrder {
ASC("asc"),
DESC("desc");
public final String sortOrder;
SortOrder(String sortOrder) {
this.sortOrder = sortOrder;
}
}
But as soon as I do this:
public class PagedRequest {
#QueryParam("sortOrder")
#DefaultValue("asc")
public SortOrder sortOrder;
}
My REST Endpoint cannot match the signature anymore and returns a 404. Why is that? I thought that the presence of a constructor accepting a single String should allow JAX-RS to do the conversion.
What am I doing wrong?
UPDATE
I managed to make it work like this, but it does not really answer my initial question...
public enum SortOrder {
ASC,
DESC;
public static SortOrder fromString(String param) {
String toUpper = param.toUpperCase();
try {
return valueOf(toUpper);
} catch (Exception e) {
return null;
}
}
}
The Enum.valueOf(String) method is used to resolve the value. Since your SorterOrder enums are uppercase you'd be required to send the parameter in uppercase.
If you want to pass the value in lowercase only you could change the enum names to lower case, e.g. SortOrder.asc.
If you don't know or don't want to care about the case the parameter is sent in you could use a ParamConverter.
public class SortOrderParamConverter implements ParamConverter<SortOrder> {
#Override
public SortOrder fromString(final String value) {
if (value != null) {
return SortOrder.valueOf(value.toUpperCase(Locale.ROOT));
}
return SortOrder.ASC;
}
#Override
public String toString(final SortOrder value) {
return value.name();
}
}
If you want a more generic approach you could create a ParamConverter or all enums.
#Provider
public class EnumParamConverterProvider implements ParamConverterProvider {
#Override
public <T> ParamConverter<T> getConverter(final Class<T> rawType, final Type genericType,
final Annotation[] annotations) {
if (!rawType.isEnum()) {
return null;
}
final Enum<?>[] constants = (Enum<?>[]) rawType.getEnumConstants();
return new ParamConverter<T>() {
#Override
#SuppressWarnings("unchecked")
public T fromString(final String value) {
if (value == null || value.isEmpty()) {
return null;
}
for (Enum<?> e : constants) {
if (e.name().equalsIgnoreCase(value)) {
return (T) e;
}
}
// No match, check toString()
for (Enum<?> e : constants) {
if (e.toString().equalsIgnoreCase(value)) {
return (T) e;
}
}
return null;
}
#Override
public String toString(final T value) {
return value != null ? value.toString() : null;
}
};
}
}

Postgres array membership test

I have a column (e.g., "nicknames") in one of my Postgres database tables ("person") that is declared as a text array (text[]). I can retrieve values from the column fine with a custom class (StringList) that implements the hibernate UserType interface. Here's my entity class
#Entity
#Table(name = "person")
public class Person {
...
#Column(columnDefinition = "text[]")
#Type(type = "com.me.type.StringList")
private List<String> nicknames;
}
How can I retrieve Person entities that contain a given nickname? I'm trying to use a Spring JPA Query as such:
#Query("SELECT p FROM Person p WHERE ...)")
List<Person> findPersonsWithNickname(String nickname );
Every attempt to complete the query has given me a runtime exception and when I place breakpoints in my StringList, they are not getting hit for this query.
Here's how StringList is defined:
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.usertype.UserType;
import java.io.Serializable;
import java.sql.Array;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class StringList implements UserType {
private final int[] arrayTypes = new int[]{Types.ARRAY};
public int[] sqlTypes() {
return arrayTypes;
}
public Class<List> returnedClass() {
return List.class;
}
public boolean equals(Object x, Object y) throws HibernateException {
return x == null ? y == null : x.equals(y);
}
public int hashCode(Object x) throws HibernateException {
return x == null ? 0 : x.hashCode();
}
#Override
public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner)
throws HibernateException, SQLException {
if (names != null && names.length > 0 && rs != null && rs.getArray(names[0]) != null) {
Object array = rs.getArray(names[0]).getArray();
if (array instanceof String[])
return Arrays.asList((String[]) array);
else
return Arrays.asList();
}
return null;
}
#Override
public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session)
throws HibernateException, SQLException {
if (value != null && st != null) {
List<String> list = (List<String>) value;
String[] castObject = list.toArray(new String[list.size()]);
Array array = session.connection().createArrayOf("text", castObject);
st.setArray(index, array);
} else {
st.setNull(index, arrayTypes[0]);
}
}
public Object deepCopy(Object value) throws HibernateException {
if (value == null)
return null;
List<String> list = (List<String>) value;
ArrayList<String> clone = new ArrayList<String>();
for (Object stringValue : list)
clone.add((String) stringValue);
return clone;
}
public boolean isMutable() {
return false;
}
public Serializable disassemble(Object value) throws HibernateException {
return (Serializable) value;
}
public Object assemble(Serializable cached, Object owner) throws HibernateException {
return cached;
}
public Object replace(Object original, Object target, Object owner) throws HibernateException {
return original;
}
}

How to convert jdbc template query result to JSON Array in java?

I am converting software from Delphi to Spring boot. I have lots of queries in an existing SQL Server database, and I want to display them.
For every query, I have to create entity class, that override row mapper and create entity class.
public class PregledTroskova {
int RbrStavke;
int RbrNaloga;
String Konto;
String SifKomint;
float Duguje;
float Potrazuje;
public PregledTroskova() {
}
public int getRbrStavke() {
return RbrStavke;
}
public void setRbrStavke(int rbrStavke) {
RbrStavke = rbrStavke;
}
public int getRbrNaloga() {
return RbrNaloga;
}
public void setRbrNaloga(int rbrNaloga) {
RbrNaloga = rbrNaloga;
}
public String getKonto() {
return Konto;
}
public void setKonto(String konto) {
Konto = konto;
}
public String getSifKomint() {
return SifKomint;
}
public void setSifKomint(String sifKomint) {
SifKomint = sifKomint;
}
public float getDuguje() {
return Duguje;
}
public void setDuguje(float duguje) {
Duguje = duguje;
}
public float getPotrazuje() {
return Potrazuje;
}
public void setPotrazuje(float potrazuje) {
Potrazuje = potrazuje;
}
}
Then after that I have to write one more class for mapper
class PregledTroskovaRowMapper implements RowMapper<PregledTroskova> {
#Override
public PregledTroskova mapRow(ResultSet resultSet, int i) throws SQLException {
PregledTroskova pregledTroskova = new PregledTroskova();
pregledTroskova.setDuguje(resultSet.getFloat("Duguje"));
pregledTroskova.setPotrazuje(resultSet.getFloat("Potrazuje"));
pregledTroskova.setRbrStavke(resultSet.getInt("RbrStavke"));
pregledTroskova.setRbrNaloga(resultSet.getInt("RbrNaloga"));
pregledTroskova.setKonto(resultSet.getString("Konto"));
pregledTroskova.setSifKomint(resultSet.getString("SifKomint"));
return pregledTroskova;
}
}
Is there any way to just generate json list/array of object where property is result set name value for all rows from select?
If you don't want to create an entity class for every query, you can return a List<Map<String, Object>> which is a list of all rows, each row is represented by a Map (column / value).
Example :
final List<Map<String, Object>> rows = jdbcTemplate.queryForList(yourQuery);
for (final Map<String, Object> row : rows) {
// do something like : row.get("yourField");
}
Example :
String sql = "select * from mytable";
result= jdbcTemplate.query(sql, new AnyObjectMapper());
Mapper (generic) :
class AnyObjectMapper implements RowMapper<Map<String, Object>> {
public AnyObjectMapper() {
// TODO Auto-generated constructor stub
}
#Override
public Map<String, Object> mapRow(ResultSet rs, int rowNum) throws SQLException {
ResultSetMetaData rsMeta = rs.getMetaData();
int colCount = rsMeta.getColumnCount();
Map<String, Object> columns = new HashMap<String, Object>();
for (int i = 1; i <= colCount; i++) {
columns.put(rsMeta.getColumnLabel(i), rs.getObject(i));
}
return columns;
}
}

Tableview update database on edit

So the thing that i want to happen, is making the tableview update the data in the database after editing it. I wanted to use the SetOnEditCommit method here. The cell editing does work, but it never gets updated, with no error either. In the first place im a bit clueless if this method is actually efficient (probably not), since its hard to find some sources for this specific thing. And the sources that i found weren't really helpful. So it would be nice if someone had an idea as to why it doesn't update, or maybe provide an alternate option here.
The mentioned part:
columnType.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<UserDetails, String>>() {
#Override
public void handle(TableColumn.CellEditEvent<UserDetails, String> event) {
updataData();
}
});
tableview.setItems(null);
tableview.setItems(data);
}
public void updataData() {
Connection connection = null;
try {
connection = DriverManager.getConnection("jdbc:mysql://37.128.148.113:3306/FYS", "FYS", "Kcj8g87~");
Statement con = connection.createStatement();
//connection
TablePosition pos = tableview.getSelectionModel().getSelectedCells().get(0);
int row = pos.getRow();
TableColumn col = pos.getTableColumn();
String data1 = (String) col.getCellObservableValue(row).getValue();
//cell
UserDetails row1 = tableview.getSelectionModel().getSelectedItem();
c1 = row1.getId();
//row
//tableview variables
con.execute("UPDATE gevonden_bagage SET type = 'data1' WHERE koffer_id = 'c1' ");
//Query
} catch (SQLException ex) {
System.err.println("Error" + ex);
}
}
//get connection, get celldata, get id data from first row, update cell with selected id
full controller class:
package simple;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TablePosition;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
/**
*
* #author admin
*/
public class FXMLUserController extends SimpleController implements Initializable {
#FXML
public TableView<UserDetails> tableview;
#FXML
public TableColumn<UserDetails, String> columnId;
#FXML
public TableColumn<UserDetails, String> columnType;
#FXML
public TableColumn<UserDetails, String> columnKleur;
#FXML
public TableColumn<UserDetails, String> columnLuchthaven;
#FXML
public TableColumn<UserDetails, String> columnKenmerken;
#FXML
public TableColumn<UserDetails, String> columnStatus;
#FXML
public TableColumn<UserDetails, String> columnDatum;
#FXML
private Button btnLoad;
//declare observable list for database data
private ObservableList<UserDetails> data;
private DbConnection dc;
String c1;
#FXML
//strings for getRow method
#Override
public void initialize(URL url, ResourceBundle rb) {
dc = new DbConnection();
loadDataFromDatabase();
}
#FXML
public void loadDataFromDatabase() {
try {
Connection conn = dc.Connect();
data = FXCollections.observableArrayList();
// Execute query and store result in a resultset
ResultSet rs = conn.createStatement().executeQuery("SELECT * FROM gevonden_bagage");
while (rs.next()) {
//get strings
data.add(new UserDetails(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5),
rs.getString(6), rs.getString(7)));
}
} catch (SQLException ex) {
System.err.println("Error" + ex);
}
//Set cell values to tableview.
tableview.setEditable(true);
tableview.getSelectionModel().setCellSelectionEnabled(true);
columnType.setCellFactory(TextFieldTableCell.forTableColumn());
columnKleur.setCellFactory(TextFieldTableCell.forTableColumn());
columnLuchthaven.setCellFactory(TextFieldTableCell.forTableColumn());
columnKenmerken.setCellFactory(TextFieldTableCell.forTableColumn());
columnStatus.setCellFactory(TextFieldTableCell.forTableColumn());
columnDatum.setCellFactory(TextFieldTableCell.forTableColumn());
//makes columns editable
columnId.setCellValueFactory(new PropertyValueFactory<>("id"));
columnType.setCellValueFactory(new PropertyValueFactory<>("type"));
columnKleur.setCellValueFactory(new PropertyValueFactory<>("kleur"));
columnLuchthaven.setCellValueFactory(new PropertyValueFactory<>("luchthaven"));
columnKenmerken.setCellValueFactory(new PropertyValueFactory<>("kenmerken"));
columnStatus.setCellValueFactory(new PropertyValueFactory<>("status"));
columnDatum.setCellValueFactory(new PropertyValueFactory<>("datum"));
columnType.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<UserDetails, String>>() {
#Override
public void handle(TableColumn.CellEditEvent<UserDetails, String> event) {
updataData();
}
});
tableview.setItems(null);
tableview.setItems(data);
}
public void updataData() {
Connection connection = null;
try {
connection = DriverManager.getConnection("jdbc:mysql://37.128.148.113:3306/FYS", "FYS", "Kcj8g87~");
Statement con = connection.createStatement();
//connection
TablePosition pos = tableview.getSelectionModel().getSelectedCells().get(0);
int row = pos.getRow();
TableColumn col = pos.getTableColumn();
String data1 = (String) col.getCellObservableValue(row).getValue();
//cell
UserDetails row1 = tableview.getSelectionModel().getSelectedItem();
c1 = row1.getId();
//row
//tableview variables
con.execute("UPDATE gevonden_bagage SET type = 'data1' WHERE koffer_id = 'c1' ");
//Query
} catch (SQLException ex) {
System.err.println("Error" + ex);
}
}
//get connection, get celldata, get id data from first row, update cell with selected id
#FXML
public void getRow() {
TablePosition pos = tableview.getSelectionModel().getSelectedCells().get(0);
int row = pos.getRow();
TableColumn col = pos.getTableColumn();
// this gives the value in the selected cell:
String data1 = (String) col.getCellObservableValue(row).getValue();
System.out.println(data1);
//CURRENTLY UNUSED METHOD
}
}
Model class:
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
/**
*
* #author admin
*/
public class UserDetails {
private final StringProperty id;
private final StringProperty type;
private final StringProperty kleur;
private final StringProperty luchthaven;
private final StringProperty kenmerken;
private final StringProperty status;
private final StringProperty datum;
//Default constructor
public UserDetails(String id, String type, String kleur, String luchthaven, String kenmerken, String status, String datum) {
this.id = new SimpleStringProperty(id);
this.type = new SimpleStringProperty(type);
this.kleur = new SimpleStringProperty(kleur);
this.luchthaven = new SimpleStringProperty(luchthaven);
this.kenmerken = new SimpleStringProperty(kenmerken);
this.status = new SimpleStringProperty(status);
this.datum = new SimpleStringProperty(datum);
}
//getters
public String getId() {
return id.get();
}
public String getType() {
return type.get();
}
public String getKleur() {
return kleur.get();
}
public String getLuchthaven() {
return luchthaven.get();
}
public String getKenmerken() {
return kenmerken.get();
}
public String getStatus() {
return status.get();
}
public String getDatum() {
return datum.get();
}
//setters
public void setId(String value) {
id.set(value);
}
public void setType(String value) {
type.set(value);
}
public void setKleur(String value) {
kleur.set(value);
}
public void setLuchthaven(String value) {
luchthaven.set(value);
}
public void setKenmerken(String value) {
kenmerken.set(value);
}
public void setStatus(String value) {
status.set(value);
}
public void setDatum(String value) {
datum.set(value);
}
//property values
public StringProperty idProperty() {
return id;
}
public StringProperty typeProperty() {
return type;
}
public StringProperty kleurProperty() {
return kleur;
}
public StringProperty luchthavenProperty() {
return luchthaven;
}
public StringProperty kenmerkenProperty() {
return kenmerken;
}
public StringProperty statusProperty() {
return status;
}
public StringProperty datumProperty() {
return datum;
}
}
From the TableView documentation:
By default the TableColumn edit commit handler is non-null, with a
default handler that attempts to overwrite the property value for the
item in the currently-being-edited row. It is able to do this as the
Cell.commitEdit(Object) method is passed in the new value, and this is
passed along to the edit commit handler via the CellEditEvent that is
fired. It is simply a matter of calling
TableColumn.CellEditEvent.getNewValue() to retrieve this value.
It is very important to note that if you call
TableColumn.setOnEditCommit(javafx.event.EventHandler) with your own
EventHandler, then you will be removing the default handler. Unless
you then handle the writeback to the property (or the relevant data
source), nothing will happen.
So the problem is that by setting the onEditCommit on columnType, you remove the default handler that actually updates typeProperty in the UserDetails instance. Consequently
String data1 = (String) col.getCellObservableValue(row).getValue();
gives the old value, and your update to the database won't change anything.
Additionally, you have errors in the way you create the SQL statement. You are making the id in the WHERE clause the literal value 'c1' (instead of the value contained in the variable c1, and similarly setting the value of type to the literal value 'data1', instead of the value in the variable data1.
Here is a fix, along with some simplification of the code and some better practices for avoiding SQL injection attacks:
columnType.setOnEditCommit(event -> {
UserDetails user = event.getRowValue();
user.setType(event.getNewValue());
updateData("type", event.getNewValue(), user.getId());
});
and then
private void updateData(String column, String newValue, String id) {
// btw it is way better to keep the connection open while the app is running,
// and just close it when the app shuts down....
// the following "try with resources" at least makes sure things are closed:
try (
Connection connection = DriverManager.getConnection("jdbc:mysql://37.128.148.113:3306/FYS", "FYS", "Kcj8g87~");
PreparedStatement stmt = connection.prepareStatement("UPDATE gevonden_bagage SET "+column+" = ? WHERE koffer_id = ? ");
) {
stmt.setString(1, newValue);
stmt.setString(2, id);
stmt.execute();
} catch (SQLException ex) {
System.err.println("Error");
// if anything goes wrong, you will need the stack trace:
ex.printStackTrace(System.err);
}
}

Custom FunctionQuery ConstValueSource

I wrote small function query which returns constant value base on key passed in.
It works great for the first request, but when I change qk it doesn't actually return anything new because it is cached.
Is there any way to force solr not to cache this function query results, or make qk key for the cache, so if I change qk it will search again?
import java.io.IOException;
import java.util.Map;
import org.apache.lucene.index.IndexReader;
import org.apache.solr.search.function.DocValues;
import org.apache.solr.search.function.ValueSource;
public class ConstValueSource extends ValueSource {
final Map<String, Float> constants;
final String qk;
final String field;
public ConstValueSource(Map<String, Float> constants, String qk, String field) {
this.constants = constants;
this.qk=qk;
this.field=field;
}
public DocValues getValues(Map context, IndexReader reader) throws IOException {
return new DocValues() {
public float floatVal(int doc) {
return constants.get(qk);
}
public int intVal(int doc) {
return (int)floatVal(doc);
}
public long longVal(int doc) {
return (long)floatVal(doc);
}
public double doubleVal(int doc) {
return (double)floatVal(doc);
}
public String strVal(int doc) {
return Float.toString(floatVal(doc));
}
public String toString(int doc) {
return description();
}
};
}
#Override
public String description() {
return field + "_" + qk;
}
#Override
public boolean equals(Object o) {
if (!(o instanceof ConstValueSource))
return false;
ConstValueSource other = (ConstValueSource) o;
return this.field.equals(other.field) && this.qk.equals(other.qk);
}
#Override
public int hashCode() {
return field.hashCode() * qk.hashCode();
}
}
Here is my value parser
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.search.FunctionQParser;
import org.apache.solr.search.ValueSourceParser;
import org.apache.solr.search.function.ValueSource;
public class ConstSourceParser extends ValueSourceParser {
public void init(NamedList namedList) {}
public ValueSource parse(FunctionQParser fqp) {
try {
SolrParams paramters = fqp.getParams();
return new ConstValueSource(data, paramters.get("qk"), "qk");
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
Ok it was issue with old cache, after updating description and clearing cache it start working.
Is there any way to filter by response?
You can control caching with meta {!cache=false}
For example: fl={!cache=false}field(your_const_field)
And in filter query: fq={!frange l=2 cache=false}field(your_const_field)
More information:
https://cwiki.apache.org/confluence/display/solr/Common+Query+Parameters
http://searchhub.org/2012/02/10/advanced-filter-caching-in-solr/

Resources