Perform Fuzzy Query in JBOSS Data Grid Remote Cache - datagrid

Currently I am trying to do Fuzzy Query with ICKLE in JBOSS Data GRID remote cache. Below is my .proto file
package quickstart;
/* #Indexed */
message Person {
/* #Field(index = true, store = true, analyze = true) */
required string name = 1;
/* #IndexedField(index = true, store = false) */
required int32 id = 2;
optional string email = 3;
optional string address = 4;
enum PhoneType {
MOBILE = 0;
HOME = 1;
WORK = 2;
}
/* #Indexed */
message PhoneNumber {
/* #Field */
required string number = 1;
/* #IndexedField(index = false, store = false) */
optional PhoneType type = 2 [default = HOME];
}
/* #Field(index = true, store = false) */
repeated PhoneNumber phone = 5;
}
}
I trying to run Below Query
private void queryPersonByNamebyIckelAndFuzzyDescription() {
String namePattern = readConsole("Enter person name pattern: ");
QueryFactory qf = Search.getQueryFactory(remoteCache);
Query query = qf.create("FROM quickstart.Person where name : '"+namePattern+"'~2");
List<Person> results = query.list();
System.out.println("Found " + results.size() + " matches:");
for (Person p : results) {
System.out.println(">> " + p);
}
}
But I am getting below Exception
org.infinispan.client.hotrod.exceptions.HotRodClientException:Request for messageId=10 returned server error (status=0x85): org.infinispan.objectfilter.ParsingException: ISPN028521: Full-text queries cannot be applied to property 'name' in type quickstart.Person unless the property is indexed and analyzed.

Modifying it in this way would help.
package quickstart;
/* #Indexed
#Analyzer(definition = "standard")*/
message Person {
/* #Field(store = Store.YES, analyze = Analyze.YES) */
required string name = 1;
......
.....

Related

Xunit CSV streamReader.ReadToEnd returns System.ArgumentOutOfRangeException

I would like to evaluate a CSV data series with Xunit.
For this I need to read in a string consisting of int, bool, double and others.
With the following code, the transfer basically works for one row.
But since I want to test for predecessor values, I need a whole CSV file for evaluation.
My [Theory] works with InlineData without errors.
But when I read in a CSV file, the CSVDataHandler gives a System.ArgumentOutOfRangeException!
I can't find a solution for the error and ask for support.
Thanks a lot!
[Theory, CSVDataHandler(false, "C:\\MyTestData.txt", Skip = "")]
public void TestData(int[] newLine, int[] GetInt, bool[] GetBool)
{
for (int i = 0; i < newLine.Length; i++)
{
output.WriteLine("newLine {0}", newLine[i]);
output.WriteLine("GetInt {0}", GetInt[i]);
output.WriteLine("GetBool {0}", GetBool[i]);
}
}
[DataDiscoverer("Xunit.Sdk.DataDiscoverer", "xunit.core")]
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public abstract class DataArribute : Attribute
{
public abstract IEnumerable<object> GetData(MethodInfo methodInfo);
public virtual string? Skip { get; set; }
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class CSVDataHandler : DataAttribute
{
public CSVDataHandler(bool hasHeaders, string pathCSV)
{
this.hasHeaders = hasHeaders;
this.pathCSV = pathCSV;
}
public override IEnumerable<object[]> GetData(MethodInfo methodInfo)
{
var methodParameters = methodInfo.GetParameters();
var paramterTypes = methodParameters.Select(p => p.ParameterType).ToArray();
using (var streamReader = new StreamReader(pathCSV))
{
if (hasHeaders) { streamReader.ReadLine(); }
string csvLine = string.Empty;
// ReadLine ++
//while ((csvLine = streamReader.ReadLine()) != null)
//{
// var csvRow = csvLine.Split(',');
// yield return ConvertCsv((object[])csvRow, paramterTypes);
//}
// ReadToEnd ??
while ((csvLine = streamReader.ReadToEnd()) != null)
{
if (Environment.NewLine != null)
{
var csvRow = csvLine.Split(',');
yield return ConvertCsv((object[])csvRow, paramterTypes); // System.ArgumentOutOfRangeException
}
}
}
}
private static object[] ConvertCsv(IReadOnlyList<object> cswRow, IReadOnlyList<Type> parameterTypes)
{
var convertedObject = new object[parameterTypes.Count];
for (int i = 0; i < parameterTypes.Count; i++)
{
convertedObject[i] = (parameterTypes[i] == typeof(int)) ? Convert.ToInt32(cswRow[i]) : cswRow[i]; // System.ArgumentOutOfRangeException
convertedObject[i] = (parameterTypes[i] == typeof(double)) ? Convert.ToDouble(cswRow[i]) : cswRow[i];
convertedObject[i] = (parameterTypes[i] == typeof(bool)) ? Convert.ToBoolean(cswRow[i]) : cswRow[i];
}
return convertedObject;
}
}
MyTestData.txt
1,2,true,
2,3,false,
3,10,true,
The first call to streamReader.ReadToEnd() will return the entire contents of the file in a string, not just one line. When you call csvLine.Split(',') you will get an array of 12 elements.
The second call to streamReader.ReadToEnd() will not return null as your while statement appears to expect, but an empty string. See the docu at
https://learn.microsoft.com/en-us/dotnet/api/system.io.streamreader.readtoend?view=net-7.0
If the current position is at the end of the stream, returns an empty
string ("").
With the empty string, the call to call csvLine.Split(',') will return an array of length 0, which causes your exception when its first element (index 0) is accessed.
All of this could have been easily discovered by simply starting the test in a debugger.
It looks like you have some other issues here as well.
I don't understand what your if (Environment.NewLine != null) is intended to do, the NewLine property will never be null but should have one of the values "\r\n" or "\n" so the if will always be taken.
The parameters of your test method are arrays int[] and bool[], but you are checking against the types int, double and bool in your ConvertCsv method, so the alternative cswRow[i] will always be returned. You'll wind up passing strings to your method expecting int[] and bool[] and will at latest get an error there.
This method reads a data series from several rows and columns and returns it as an array for testing purposes.
The conversion of the columns can be adjusted according to existing pattern.
Thanks to Christopher!
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class CSVDataHandler : Xunit.Sdk.DataAttribute
{
public CSVDataHandler(string pathCSV)
{
this.pathCSV = pathCSV;
}
public override IEnumerable<object[]> GetData(MethodInfo methodInfo)
{
List<int> newLine = new();
List<int> GetInt = new();
List<bool> GetBool = new();
var reader = new StreamReader(pathCSV);
string readData = string.Empty;
while ((readData = reader.ReadLine()) != null)
{
string[] split = readData.Split(new char[] { ',' });
newLine.Add(int.Parse(split[0]));
GetInt.Add(int.Parse(split[1]));
GetBool.Add(bool.Parse(split[2]));
// Add more objects ...
}
yield return new object[] { newLine.ToArray(), GetInt.ToArray(), GetBool.ToArray() };
}
}

spring data redis use #RedisHash to generate hash then retrieve its fields

friends! I want to retrieve only a field of a hash from redis database using spring RedisTemplate, but it does not work. Because I think it is reasonable to do it since #RedisHash makes the object a hash table in Redis, I have tried to retrieve or update part of the hash, but don't know why it does not work:
This is the entity I use:
#Data
#RedisHash("arithmetic_gamestats")
public class GameStats {
/**
* Used for redis serialization
*/
public GameStats() {}
public GameStats(long userId, int score) {
this.userId = userId;
this.score = score;
}
public GameStats(long userId, int score, List<Badge> badges) {
this.userId = userId;
this.score = score;
this.badges = badges;
}
#Id
private Long userId;
private int score;
private List<Badge> badg/es;
}
// this is my test, first I create a new object, and save it to redis, this works totally fine:
//#Test #Order(5)
public void testRedisHashtable() {
long userId = userIds.get(random.nextInt(0, userIds.size()));
GameStats gameStats = new GameStats(userId, 1000);
GameStats dbGameStats = gamestatsRepository.save(gameStats);
assertThat(dbGameStats).isNotNull();
}
After insert one instance of the GameStats class in the test method, I get the following result in Redis server which is what I expected:
127.0.0.1:6379> keys *
1) "arithmetic_gamestats"
2) "arithmetic_gamestats:-5461129489864155017"
127.0.0.1:6379> type "arithmetic_gamestats"
set
127.0.0.1:6379> type "arithmetic_gamestats:-5461129489864155017"
hash
127.0.0.1:6379> smembers "arithmetic_gamestats"
1) "-5461129489864155017"
127.0.0.1:6379> hgetall "arithmetic_gamestats:-5461129489864155017"
1) "_class"
2) "com.worldexplorer.arithmeticgamification.entity.GameStats"
3) "score"
4) "1000"
5) "userId"
6) "-5461129489864155017"
127.0.0.1:6379> hget "arithmetic_gamestats:-5461129489864155017" "score"
"1000"
I copy the key from redis to retrieve the data, but the result is null, or empty:
#Test #Order(6)
public void testRedisHash() {
String key = "arithmetic_gamestats:-5461129489864155017";
Object scoreObject = redisTemplate.opsForHash().get(key, "score");
System.out.println("score = " + scoreObject);
Set<Object> keySet = redisTemplate.opsForHash().keys(key);
for (Object object : keySet) {
System.out.println("key = " + object);
}
Map<Object, Object> keyvalueMap = redisTemplate.opsForHash().entries(key);
for (Map.Entry<Object, Object> entry : keyvalueMap.entrySet()) {
System.out.println("key-value = " + entry.getKey() + "-" + entry.getValue());
}
System.out.println("keySet = " + keySet);
System.out.println("keyvalueMap = " + keyvalueMap);
}
This is the result printed in the console:
score = null
keySet = []
keyvalueMap = {}
And here is the repository:
public interface GamestatsRepository extends CrudRepository<GameStats, Long>{
}

Is it possible to check if an SQLite table exists.

I have the following code:
dbcon = DependencyService.Get<ISQLite>().GetConnection();
// create the tables
dbcon.CreateTable<Category>();
dbcon.CreateTable<Settings>();
var settings = dbcon.Table<Settings>().ToList();
if (settings.Count <= 0)
{
var noa = new Settings { Setting = "NumberOfAnswers", Value = 5 };
var cfs = new Settings { Setting = "CardFrontSide", Value = 0 };
dbcon.Insert(noa);
dbcon.Insert(cfs);
}
var categories = dbcon.Table<Category>().ToList();
if (categories.Count <= 0)
{
InsertCategory();
}
From what I can see the application is using SQLite-net
What I would like to know is if there is a way I can check to see if a table exists rather than do this which is to try and create it anyway and then try to check if it has rows in it.
This query will return the list of tables in the database
SELECT * FROM sqlite_master WHERE type = 'table';
You can filter it down to a single row for an "exists" check.
SELECT * FROM sqlite_master WHERE type = 'table' AND tbl_name = 'xyz';
You can do something like this:
public static bool TableExists<T> (SQLiteConnection connection)
{
const string cmdText = "SELECT name FROM sqlite_master WHERE type='table' AND name=?";
var cmd = connection.CreateCommand (cmdText, typeof(T).Name);
return cmd.ExecuteScalar<string> () != null;
}
Source
You can use the below codes
public bool IsTableExists(string tableName)
{
try
{
var tableInfo = database.GetConnection().GetTableInfo(tableName);
if(tableInfo.Count > 0)
{
return true;
}
else
{
return false;
}
}
catch
{
return false;
}
}
public SQLiteAsyncConnection database;
public ClientDatabase(string dbPath)
{
database = new SQLiteAsyncConnection(dbPath);
}

How to update dictionary in Swift located at every index of Array

This response is coming from server in JSON format
posts =
(
{
commentCount = 0;
"country_id" = 225;
"country_name" = "United States";
dislikeCount = 2;
disliked = 0;
firstname = Test;
imageHeight = 0;
imagePath = "";
imageWidth = 0;
lastname = Test;
likeCount = 2;
liked = 0;
postid = 126;
posttime = "2014-11-10 12:26:43";
shareCount = 0;
statusUpdate = Hello;
"upload_type" = text;
userId = 13;
userimage = "https://Test.com/1409976093.png";
videoHeight = "";
videoPath = "";
videoThumbnail = "";
videoWidth = "";
},
{
commentCount = 0;
"country_id" = 225;
"country_name" = "United States";
dislikeCount = 2;
disliked = 0;
firstname = Test;
imageHeight = 0;
imagePath = "";
imageWidth = 0;
lastname = Test;
likeCount = 3;
liked = 0;
postid = 125;
posttime = "2014-10-28 17:50:00";
shareCount = 0;
statusUpdate = "Happy%20chhata%20puja%20to%20you%20and%20your%20family%0Athanks%0ADr%20shah%20family";
"upload_type" = text;
userId = 78;
userimage = "https://Test.com/1410142960.png";
videoHeight = "";
videoPath = "";
videoThumbnail = "";
videoWidth = "";
}
Now I need to update the value of "liked" from 0 to 1 locally but I am not able to do that. I have stored this array in my array like this:
self.homePageDataArray.addObjectsFromArray(dictionary["posts"] as NSMutableArray)
And I am able to fetch the content from every index and also able to show this in TableView but I want to changed the status of "liked" from 0 to 1 when user will tap on the "Like Button" in my app. Obviously I will update this on server but I want to update that locally as well parallely.
Please let me know how it can be achieved. I tried a lot but every time it is showing some error! For Instance,
var tempDic:Dictionary<AnyObject,AnyObject> = self.homePageDataArray[selectedRow] as Dictionary
I am getting this error
Type 'AnyObject' does not conform to protocol 'Hashable'
Ultimately, I want to able to able to use the "updateValue" method so that I can update the value of my dictionary in my array.
This should work for you:
var tempDic = self.homePageDataArray[selectedRow] as Dictionary<String, AnyObject>
Your version:
var tempDic:Dictionary<AnyObject,AnyObject> = self.homePageDataArray[selectedRow] as Dictionary
Will not work because AnyObject is not conformable to Hashable, a requirement for the generic key type in Dictionary.
And to answer your other question:
var tempDic = self.homePageDataArray[selectedRow] as NSMutableDictionary as Dictionary
The statement above compiles because Dictionary is bridgeable to it's Objective-C counterpart; NSMutableDictionary. Your resultant dictionary will be of type Dictionary<String, AnyObject>. You're probably wondering how the type String was inferred. Well, NSMutableDictionary uses NSString as keys, a type which is bridgeable to it's Swift counterpart, you guessed it; String.
I really don't know WHY, but following solution worked for me
var tempDic = self.homePageDataArray[selectedRow] as NSMutableDictionary as Dictionary
If anyone can explain then it will help others also!

Can I generate SQL scripts with ServiceStack OrmLite?

Is it possible to generate SQL scripts using OrmLite without executing it against a database? I would like to load a list of DTOs from a live SqlServer database and output a script to DELETE and INSERT each record.
The provided mini profiler supports logging, but looks like it needs to wrap a real database connection.
This is trivial now that OrmLite extension methods are now mockable by providing your own OrmLiteResultsFilter.
E.g. this ResultsFilter below records every sql statement executed and inherts the behavior from OrmLiteResultsFilter to return empty results:
public class CaptureSqlFilter : OrmLiteResultsFilter
{
public CaptureSqlFilter()
{
SqlCommandFilter = CaptureSqlCommand;
SqlCommandHistory = new List<SqlCommandDetails>();
}
private void CaptureSqlCommand(IDbCommand command)
{
SqlCommandHistory.Add(new SqlCommandDetails(command));
}
public List<SqlCommandDetails> SqlCommandHistory { get; set; }
public List<string> SqlStatements
{
get { return SqlCommandHistory.Map(x => x.Sql); }
}
}
You can wrap this in an using scope to capture each SQL statement without executing them, e.g:
using (var captured = new CaptureSqlFilter())
using (var db = OpenDbConnection())
{
db.CreateTable<Person>();
db.Select<Person>(x => x.Age > 40);
db.Single<Person>(x => x.Age == 42);
db.Count<Person>(x => x.Age < 50);
db.Insert(new Person { Id = 7, FirstName = "Amy", LastName = "Winehouse" });
db.Update(new Person { Id = 1, FirstName = "Jimi", LastName = "Hendrix" });
db.Delete<Person>(new { FirstName = "Jimi", Age = 27 });
db.SqlColumn<string>("SELECT LastName FROM Person WHERE Age < #age",
new { age = 50 });
db.SqlList<Person>("exec sp_name #firstName, #age",
new { firstName = "aName", age = 1 });
db.ExecuteNonQuery("UPDATE Person SET LastName={0} WHERE Id={1}"
.SqlFmt("WaterHouse", 7));
var sql = string.Join(";\n\n", captured.SqlStatements.ToArray());
sql.Print();
}
Which prints out:
CREATE TABLE "Person"
(
"Id" INTEGER PRIMARY KEY,
"FirstName" VARCHAR(8000) NULL,
"LastName" VARCHAR(8000) NULL,
"Age" INTEGER NOT NULL
);
;
SELECT "Id", "FirstName", "LastName", "Age"
FROM "Person"
WHERE ("Age" > 40);
SELECT "Id", "FirstName", "LastName", "Age"
FROM "Person"
WHERE ("Age" = 42)
LIMIT 1;
SELECT COUNT(*) FROM "Person" WHERE ("Age" < 50);
INSERT INTO "Person" ("Id","FirstName","LastName","Age") VALUES (#Id,#FirstName,#LastName,#Age);
UPDATE "Person" SET "FirstName"=#FirstName, "LastName"=#LastName, "Age"=#Age WHERE "Id"=#Id;
DELETE FROM "Person" WHERE "FirstName"=#FirstName AND "Age"=#Age;
SELECT LastName FROM Person WHERE Age < #age;
exec sp_name #firstName, #age;
UPDATE Person SET LastName='WaterHouse' WHERE Id=7
More examples available in CaptureSqlFilterTests.cs
As CaptureSqlFilter is useful I've just added it to OrmLite in this commit which will be in the next v4.0.20 that's now available on MyGet.
Using the DialectProvider directly seems to work well enough for what I need. ToInsertRowStatement takes a IDbCommand paramater, but does not use it so null works.
OrmLiteConfig.DialectProvider = SqlServerOrmLiteDialectProvider.Instance;
var dto = new PersonDTO { Id = Guid.NewGuid(), Name = "Carl" };
var deleteText = SqlServerOrmLiteDialectProvider.Instance.ToDeleteRowStatement(dto);
var insertText = SqlServerOrmLiteDialectProvider.Instance.ToInsertRowStatement((IDbCommand)null, dto);
Is there a better alternative?
I use this to capture the statement and keep running the sentense.
public class CustomOrmLiteExecFilter : OrmLiteExecFilter
{
public override T Exec<T>(IDbConnection dbConn, Func<IDbCommand, T> filter)
{
var holdProvider = OrmLiteConfig.DialectProvider;
var dbCmd = CreateCommand(dbConn);
try
{
var ret = filter(dbCmd);
var pureSQL = holdProvider.MergeParamsIntoSql(dbCmd.CommandText, dbCmd.Parameters.OfType<IDbDataParameter>());
//log or save the SQL Statement
return ret;
}
finally
{
if (OrmLiteConfig.DialectProvider != holdProvider)
OrmLiteConfig.DialectProvider = holdProvider;
}
}
}
and the usage:
OrmLiteConfig.ExecFilter = new CustomOrmLiteExecFilter();
hope this can help you!

Resources