Issues in indexing or querying - search

every one I m a beginner with Big Data and trying to index and search the data. I have a problem
1)- While indexing program runs very smoothly but while Searching It always shows one or zero hit per query.
Like this:-
Skipped write.lock
Added: D:\Studies\Universities-Punjab University-\Notes\Final Year Project\Appache Lucene\Result 3\file.txt
Added: D:\Studies\Universities-Punjab University-\Notes\Final Year Project\Appache Lucene\Result 3\lab 1.txt
2 Documents Added.
Enter the Search Query (q=quit):
Waleed
Found 1 hits.
D:\Studies\Universities-Punjab University-\Notes\Final Year Project\Appache Lucene\Result 3\file.txt score=0.0390625
Enter the Search Query (q=quit):
Wlaeed
Found 0 hits.
Enter the Search Query (q=quit):
Ahmad
Found 1 hits.
D:\Studies\Universities-Punjab University-\Notes\Final Year Project\Appache Lucene\Result 3\file.txt score=0.0390625
Enter the Search Query (q=quit):
train
Found 1 hits.
D:\Studies\Universities-Punjab University-\Notes\Final Year Project\Appache Lucene\Result 3\lab 1.txt score=0.17900687
Enter the Search Query (q=quit):
q
Code for Indexing:-
Reader fr = null;
try {
Document doc = new Document();
fr = new FileReader(f);
doc.add(new StringField("path", f.getPath(), Field.Store.YES));
doc.add(new StringField("filename", f.getName(),Field.Store.YES));
doc.add(new TextField("contents", fr));
writer.addDocument(doc);
enhanceList(f, helper);
} catch (Exception e) {
System.out.println("Could Not Add: " + f);
} finally {
fr.close();
}
Code for Searching/Querying:-
void searching() throws IOException {
String s = "";
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
IndexReader reader = DirectoryReader.open(FSDirectory.open(new File(directory)));
IndexSearcher searcher = new IndexSearcher(reader);
while (!s.equalsIgnoreCase("q")) {
try {
System.out.println("Enter the Search Query (q=quit):");
s = br.readLine();
if (s.equalsIgnoreCase("q")) {
break;
}
Query q = new QueryParser(Version.LUCENE_44, "contents", analyzer).parse(s);
ScoreDoc[] hits = searcher.search(q, 1000).scoreDocs;
System.out.println("Found " + hits.length + " hits.");
for (int i = 0; i < hits.length; i++) {
int docId = hits[i].doc;
Document d = searcher.doc(docId);
System.out.println((i + 1) + ". " + d.get("path") + " score=" + hits[i].score);
}
} catch (Exception e) {
System.out.println("Error Searching " + s + " : " + e.getMessage());
}
}
}
Please any body help me out in finding out the solution..

Related

I have this array class that is not removing items after re-running my recyclerview

The below class is used in an array.
package com.example.ShivitoMGO;
public class RoomTable {
public String RoomName,UpDown,minmaxint;
}
Main Activity
static ArrayList <RoomTable> CountCheck = new ArrayList<>();
public void playerup(View vvv){
st_spinner = v1.findViewById(R.id.spinner);
st_reportLayout = v1.findViewById(R.id.reportlayout);
st_Leanervidimg = v1.findViewById(R.id.Linearvidcopy);
TextView roomname = v1.findViewById(R.id.action_Players1);
RoomTable roomtb = new RoomTable();
if (CountCheck.size() == 0){
//playerupdown = "up";
Toast.makeText(this, "Will notify when " + mRooms.get(position1) + " players increase #" + mRoomSize.get(position1), Toast.LENGTH_LONG).show();
String[] minmaxval = mRoomSize.get(position1).split("/");
CountCheckint = Integer.parseInt(minmaxval[0].trim());
//CountCheck = (String) mRooms.get(position1);
roomtb.RoomName = (String) mRooms.get(position1);
roomtb.minmaxint = minmaxval[0].trim();
roomtb.UpDown = "up";
Log.d("added: ", "it was added");
CountCheck.add(roomtb);
Log.d("RoomTableadd: ",roomtb.RoomName+ " " + roomtb.minmaxint +" " +roomtb.UpDown);
st_reportLayout.setVisibility(View.GONE);
Log.d("Longclickhere: ", mRoomSize.get(position1));
Log.d("RoomNameCount ", String.valueOf(CountCheck.get(0).RoomName));
}else {
int exist1 = 0;
int poss;
for (int i = 0; i < CountCheck.size(); i++) {
if (roomname.getText() == CountCheck.get(i).RoomName) {
Log.d("RoomNametxt: " , CountCheck.get(i).RoomName);
Log.d("RoomNametxt: ", (String) roomname.getText());
Toast.makeText(this, "Notification " + CountCheck.get(i).RoomName + " OFF!", Toast.LENGTH_LONG).show();
Log.d("Removed item: ", String.valueOf(CountCheck.size()));
CountCheck.remove(i);
Log.d("Removed item: ", String.valueOf(CountCheck.size()));
st_reportLayout.setVisibility(View.GONE);
exist1 = 1;
poss = i;
} else {
exist1 = 0;
}
}
if (exist1 == 0) {
Toast.makeText(this, "Will notify when " + mRooms.get(position1) + " players increase #" + mRoomSize.get(position1), Toast.LENGTH_LONG).show();
String[] minmaxval = mRoomSize.get(position1).split("/");
CountCheckint = Integer.parseInt(minmaxval[0].trim());
//CountCheck = (String) mRooms.get(position1);
roomtb.RoomName = (String) mRooms.get(position1);
roomtb.minmaxint = minmaxval[0].trim();
roomtb.UpDown = "up";
Log.d("added: ", "it was added");
CountCheck.add(roomtb);
Log.d("RoomTableadd: ", roomtb.RoomName + " " + roomtb.minmaxint + " " + roomtb.UpDown);
st_reportLayout.setVisibility(View.GONE);
}
Log.d("CountSize: ", String.valueOf(CountCheck.size()));
for (int xb = 0;xb<CountCheck.size();xb++) {
try {
Log.d("RoomNameCount ", String.valueOf(CountCheck.get(xb).RoomName));
} catch (Exception e) {
Log.d("Out of range ", String.valueOf(e));
}
}
}
}
Recycler-View
#Override
public boolean onLongClick(View v) {
// Launch your web intent
if (CountCheck.size() != 0){
Log.d("Longclickhere: ",mRoomSize.get(position));
Toast.makeText(mContext, mRoomSize.get(position), Toast.LENGTH_SHORT).show();
Toast.makeText(mContext, "Will notify when "+mRooms.get(position)+" players decrease", Toast.LENGTH_SHORT).show();
String[] minmaxval = mRoomSize.get(position).split("/");
MainActivity.CountCheckint = Integer.parseInt(minmaxval[0].trim());
} else{
//MainActivity.CountCheck = "";
Toast.makeText(mContext, "Player Decrease notification OFF", Toast.LENGTH_SHORT).show();
}
return true;
In this app the recycler view creates the "rooms" and if the room is selected the textview and 2 other values are put in to the RoomTable. these are stored and used in a service to check if ether of the other to values change. Everything works as intended unless i use the swip-to-refresh witch runs the recycler-view again. If i do not refresh and i select the same item in the recycler-view it will remove it from CountCheck . However if i run the refresh and select the same recycler-view item that i selected previously it will add it instead of removing it. This Makes no since to me because i use a for loop to Check the CountCheck.get(i).RoomName aka the textview and if the names are the same then my if statement will remove instead of add. is it somehow possible i'm ending up with 2 CountCheck Objects????? with the same name???? Please I'm out of ideas on this one. Thanks.
I dont remember why. Maybe someone can explain but i changed this line
if (roomname.getText() == CountCheck.get(i).RoomName)
To this
if (roomname.getText().equals(CountCheck.get(i).RoomName));
and that fixed the issue. please let me know the difference if you are reading this.

Storing object in concurrenthashmap created using constructor

This is my code. Am trying to add employees dynamically to the concurrenthashmap. There is no error but i get inputMismatchException. Experts, please help.
CODE:
try {
System.out.println("No of employees: ");
int count = userdata.nextInt();
System.out.println("count: " + count);
System.out.println("enter employee details.");
// with ConcurrentHashMap
ConcurrentHashMap<Integer, employee> employeeDetails = new ConcurrentHashMap<>();
int index = 0;
do {
employeeDetails.put(index, new employee(userdata.nextInt(), userdata.nextLine(), userdata.nextLine()));
index++;
count--;
} while (count != 0);
System.out.println(employeeDetails.toString());
System.out.println("enter item to remove: ");
String removeValue = userdata.nextLine();
employeeDetails.forEach((k, v) -> {
if (v.equals(removeValue)) {
employeeDetails.remove(k);
}
});
System.out.println("afer removal: \n" + employeeDetails.toString());
} catch (Exception e) {
e.printStackTrace();
}
Output:
No of employees:
2
count: 2
enter employee details.
1
name
city
java.util.InputMismatchException

How to get an existing MediaContainerModel in hybris?

I tried to get MediaFormatModel, MediaModel, MediaFolderModel etc with the help of MediaService but only the MediaContainer is not possible to get from MediaService and I tried with ModelService. Only one possibility I found that by getting MediaModel we can get the MediaContainerModel but I need to get specific MediaContainerModel by passing qualifier. Like for example:
final MediaModel mm1 = mediaService.getMedia(catalogVersion, "picture515x515");
final MediaFormatModel mf1200 = mediaService.getFormat("1200x1200");
final MediaFolderModel mfm = mediaService.getFolder("convertedimages");
any help?
You can always retrieve models using the flexiblesearh getModelByExample
CatalogVersionModel catalogVersion = catalogVersionService.getCatalogVersion("yourCatalogName", "version");
MediaContainerModel container = new MediaContainerModel();
container.setCatalogVersion(catalogVersion);
container.setQualifier("yourQualifier");
try
{
container = flexibleSearchService.getModelByExample(container);
}//no container found
catch (final ModelNotFoundException ex)
{
...
}
private MediaContainerModel getExistingMediaContainer(CatalogVersionModel catalogVersion, String qualifier) {
final String query = "SELECT {" + MediaContainerModel.PK + "} FROM {" + MediaContainerModel._TYPECODE + "} "
+ "WHERE {" + MediaContainerModel.QUALIFIER + "} = ?qualifier AND " + "{" + MediaContainerModel.CATALOGVERSION + "} = ?catalogVersion";
final FlexibleSearchQuery fQuery = new FlexibleSearchQuery(query);
fQuery.addQueryParameter("qualifier", qualifier);
fQuery.addQueryParameter("catalogVersion", catalogVersion);
final SearchResult<MediaContainerModel> searchResult = flexibleSearchService.search(fQuery);
if (searchResult.getTotalCount() > 0) {
return searchResult.getResult().get(0);
} else {
return null;
}
}
I got the solution we can get as follows
#Autowired
MediaContainerService mediaContainerService;......
MediaContainerModel mediaContainer = null;
try
{
mediaContainer = mediaContainerService.getMediaContainerForQualifier("testContainer");
}
catch (final Exception e)
{
mediaContainer = createMediaContainer("testContainer");
}
mediaContainer.setCatalogVersion(catalogVersion);

Update a SavedQuery (View) from the SDK

I am trying to change all the Business Unit references I got after importing a solution to the ones in the Acceptance environment.
QueryExpression ViewQuery = new QueryExpression("savedquery");
String[] viewArrayFields = { "name", "fetchxml" };
ViewQuery.ColumnSet = new ColumnSet(viewArrayFields);
ViewQuery.PageInfo = new PagingInfo();
ViewQuery.PageInfo.Count = 5000;
ViewQuery.PageInfo.PageNumber = 1;
ViewQuery.PageInfo.ReturnTotalRecordCount = true;
EntityCollection retrievedViews = service.RetrieveMultiple(ViewQuery);
//iterate though the values and print the right one for the current user
int oldValues = 0;
int accValuesUpdated = 0;
int prodValuesUpdated = 0;
int total = 0;
foreach (var entity in retrievedViews.Entities)
{
total++;
if (!entity.Contains("fetchxml"))
{ }
else
{
string fetchXML = entity.Attributes["fetchxml"].ToString();
for (int i = 0; i < guidDictionnary.Count; i++)
{
var entry = guidDictionnary.ElementAt(i);
if (fetchXML.Contains(entry.Key.ToString().ToUpperInvariant()))
{
Console.WriteLine(entity.Attributes["name"].ToString());
oldValues++;
if (destinationEnv.Equals("acc"))
{
accValuesUpdated++;
Console.WriteLine();
Console.WriteLine("BEFORE:");
Console.WriteLine();
Console.WriteLine(entity.Attributes["fetchxml"].ToString());
string query = entity.Attributes["fetchxml"].ToString();
query = query.Replace(entry.Key.ToString().ToUpperInvariant(), entry.Value.AccGuid.ToString().ToUpperInvariant());
entity.Attributes["fetchxml"] = query;
Console.WriteLine();
Console.WriteLine("AFTER:");
Console.WriteLine();
Console.WriteLine(entity.Attributes["fetchxml"].ToString());
}
else
{
prodValuesUpdated++;
string query = entity.Attributes["fetchxml"].ToString();
query = query.Replace(entry.Key.ToString().ToUpperInvariant(), entry.Value.ProdGuid.ToString().ToUpperInvariant());
entity.Attributes["fetchxml"] = query;
}
service.Update(entity);
}
}
}
}
Console.WriteLine("{0} values to be updated. {1} shall be mapped to acceptance, {2} to prod. Total = {3} : {4}", oldValues, accValuesUpdated, prodValuesUpdated, total, retrievedViews.Entities.Count);
I see that the new value is corrected, but it does not get saved. I get no error while updating the record and publishing the changes in CRM does not help.
Any hint?
According to your comments, it sounds like the value you're saving the entity as, is the value that you want it to be. I'm guessing your issue is with not publishing your change. If you don't publish it, it'll still give you the old value of the FetchXml I believe.
Try calling this method:
PublishEntity(service, "savedquery");
private void PublishEntity(IOrganizationService service, string logicalName)
{
service.Execute(new PublishXmlRequest()
{
ParameterXml = "<importexportxml>"
+ " <entities>"
+ " <entity>" + logicalName + "</entity>"
+ " </entities>"
+ "</importexportxml>"
});
}

Subsonic - Simple Query

I have a table has 2 columns
Val1 int
Val2 int
My query very simple.
I want to get collection of record have condition (val1=Val2) ,
equivalent to (Select * from table where Val1=Val2)
I try
IDataReader rdr = new Query("Table").WHERE("Val1=Val2").ExecuteReader();
tableColl.LoadAndCloseReader(rdr);
rdr.Close();
and
..WHERE (" 'Val1=Val2' ")
..WHERE (Table.Columns.Val1,IsEqualTo,Table.Columns.Val2) //This not reguler I know
..WHERE ("Val"+'='+"Val2")
.....
any help be more apricated.
Thanks.
Unfortunately you'll need to do this as an inline query as far as I know:
TableCollection tableCollection = new InlineQuery()
.ExecuteAsCollection<TableCollection>(
"SELECT * FROM " + Table.Schema.TableName " WHERE " + Table.Columns.Val1 + " = " + Table.Columns.Val2);
was in same situation recently and came up with this:
TableCollection tablecollection = new TableCollection;
Comparison comp = Comparison.Equals;
tablecollection.Where(Table.Columns.Val1, comp, Table.Columns.Val2);
tablecollection.Load();
i found this better because i don't like inline queries. and it gives
more flexibility if you wish to allow for adhoc querying in you app.
private void CreateDynamicControls()
{
panGvHolder.Controls.Clear();
Query qry = Northwind.Product.CreateQuery();
qry.Columns.AddRange(Northwind.Product.Schema.Columns);
qry.WHERE("UnitPrice > 15").AND("UnitsInStock < 20 ");
//WHERE("UnitPrice > 15").AND("UnitsInStock < 30 ");
using (IDataReader rdr = qry.ExecuteReader())
{
Response.Write("<table>");
while (rdr.Read())
{
Response.Write("<tr>");
for (int i = 0; i < rdr.FieldCount; i++)
{
Response.Write("<td>");
Response.Write(rdr[i].ToString() + " ");
Response.Write("<td>");
} //eof for
Response.Write("</br>");
Response.Write("</tr>");
}
Response.Write("<table>");
}
} //eof method

Resources