How to set select attributes for a Document in an index - elasticsearch

How to set select attributes for a Document in an index, using spring-data-elasticsearch
for example update foo_index set attr1=<attr1_value> where id=<document.id>

Use an UpdateQuery (following code is taken from https://github.com/spring-projects/spring-data-elasticsearch/blob/a2ca312fb2812bd34781206e47be31e9e43dac00/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchTemplateTests.java#L1565-L1594):
#Test
public void shouldDoPartialUpdateForExistingDocument() {
// given
String documentId = nextIdAsString();
String messageBeforeUpdate = "some test message";
String messageAfterUpdate = "test message";
SampleEntity sampleEntity = SampleEntity.builder().id(documentId).message(messageBeforeUpdate)
.version(System.currentTimeMillis()).build();
IndexQuery indexQuery = getIndexQuery(sampleEntity);
operations.index(indexQuery, index);
indexOperations.refresh();
org.springframework.data.elasticsearch.core.document.Document document = org.springframework.data.elasticsearch.core.document.Document
.create();
document.put("message", messageAfterUpdate);
UpdateQuery updateQuery = UpdateQuery.builder(documentId)//
.withDocument(document) //
.build();
// when
operations.update(updateQuery, index);
// then
SampleEntity indexedEntity = operations.get(documentId, SampleEntity.class, index);
assertThat(indexedEntity.getMessage()).isEqualTo(messageAfterUpdate);
}

Related

Dynamics CRM Solution Import via SDK is not working

I have the below code that imports a solution into CRM Dynamics.
The code executes successfully and the import job data returns a result of success. How ever when I look for the solution in Settings->Solutions it is not there. Can anyone suggest a fix?
private void ImportSolution(string solutionPath)
{
byte[] fileBytes = File.ReadAllBytes(solutionPath);
var request = new ImportSolutionRequest()
{
CustomizationFile = fileBytes,
ImportJobId = Guid.NewGuid()
};
var response = _settings.DestinationSourceOrgService.Execute(request);
var improtJob = new ImportJob(_settings);
var importJobResult = improtJob.GetImportJob(request.ImportJobId);
var data = importJobResult.Attributes["data"].ToString();
var jobData = new ImportJobData(data);
var filePath = $#"{this._settings.SolutionExportDirectory}\Logs\";
var fileName = $#"{filePath}{jobData.SolutionName}.xml";
Directory.CreateDirectory(filePath);
File.WriteAllText(fileName, data);
PrintResult(jobData.Result, jobData.SolutionName);
}
public class ImportJob
{
private readonly ConfigurationSettings _settings;
public ImportJob(ConfigurationSettings settings)
{
_settings = settings;
}
public Entity GetImportJob(Guid importJobId)
{
var query = new QueryExpression
{
EntityName = "importjob",
ColumnSet = new ColumnSet("importjobid", "data", "solutionname"),
Criteria = new FilterExpression()
};
var result = _settings.DestinationSourceOrgService.Retrieve("importjob", importJobId, new ColumnSet("importjobid", "data", "solutionname", "progress"));
return result;
}
}
Thre ImportSolutionResponse does not contain any information as per the screen shot below.

An issue with editable JFX TableView

I have a little issue with an editable TableView. I want to display data from the database and also be able to edit then which saves it back to the DB.
Now, I can edit it. I have an if statement which checks whether the value is blank (empty or white space) and it works properly, the item in DB doesn't get updated if the value is blank.
My issue is that the blank value still gets displayed. If I click to edit it again, it displays the proper value. Here is a picture of the issue.
Here is the method which creats the table in my view class.
private TableView<Teacher> createTable(){
TableView table = new TableView();
table.setEditable(true);
table.setPrefWidth(500);
table.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
nameColumn = new TableColumn<>("Jméno");
surnameColumn = new TableColumn<>("Příjmení");
nickColumn = new TableColumn<>("Nick");
table.getColumns().addAll(nameColumn, surnameColumn, nickColumn);
int columnCount = table.getColumns().size();
double columnSize = Math.floor(table.getPrefWidth() / columnCount);
nameColumn.setPrefWidth(columnSize);
surnameColumn.setPrefWidth(columnSize);
nickColumn.setPrefWidth(columnSize);
nameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
surnameColumn.setCellValueFactory(new PropertyValueFactory<>("surname"));
nickColumn.setCellValueFactory(new PropertyValueFactory<>("nick"));
List<Teacher> list = new TeacherDao().getAllTeachers();
ObservableList<Teacher> observableList = FXCollections.observableArrayList(list);
table.setItems(observableList);
return table;
}
Here is the part of the controller class to handle the edits.
private void onEditAction(){
view.getNameColumn().setCellFactory(TextFieldTableCell.forTableColumn());
view.getNameColumn().setOnEditCommit(
new EventHandler<TableColumn.CellEditEvent<Teacher, String>>() {
#Override
public void handle(TableColumn.CellEditEvent<Teacher, String> col) {
String newValue = col.getNewValue();
if(!(CheckString.isBlank(newValue))) {
(col.getTableView().getItems().get(
col.getTablePosition().getRow())
).setName(col.getNewValue());
Teacher teacher = view.getTeacherTableView().getSelectionModel().getSelectedItem();
int id = teacher.getUser_id();
new TeacherDao().updateTeacherNick(id, newValue);
}
}
}
);
view.getSurnameColumn().setCellFactory(TextFieldTableCell.forTableColumn());
view.getSurnameColumn().setOnEditCommit(
new EventHandler<TableColumn.CellEditEvent<Teacher, String>>() {
#Override
public void handle(TableColumn.CellEditEvent<Teacher, String> col) {
String newValue = col.getNewValue();
if(!(CheckString.isBlank(newValue))) {
(col.getTableView().getItems().get(
col.getTablePosition().getRow())
).setName(col.getNewValue());
Teacher teacher = view.getTeacherTableView().getSelectionModel().getSelectedItem();
int id = teacher.getUser_id();
new TeacherDao().updateTeacherNick(id, newValue);
}
}
}
);
view.getNickColumn().setCellFactory(TextFieldTableCell.forTableColumn());
view.getNickColumn().setOnEditCommit(
new EventHandler<TableColumn.CellEditEvent<Teacher, String>>() {
#Override
public void handle(TableColumn.CellEditEvent<Teacher, String> col) {
String newValue = col.getNewValue();
if(!(CheckString.isBlank(newValue))) {
(col.getTableView().getItems().get(
col.getTablePosition().getRow())
).setName(col.getNewValue());
Teacher teacher = view.getTeacherTableView().getSelectionModel().getSelectedItem();
int id = teacher.getUser_id();
new TeacherDao().updateTeacherNick(id, newValue);
}
}
}
);
}
I also tried adding, it didn't help though.
else
(col.getTableView().getItems().get(
col.getTablePosition().getRow())
).setName(col.getOldValue());
Well, I managed to solve it, here is how if anyone is curious
public class TeacherTableView extends TableView {
private TableColumn<Teacher, String> nameColumn, surnameColumn, nickColumn;
TeacherTableView() {
createTable();
onEditAction();
}
private void createTable(){
setEditable(true);
setPrefWidth(500);
getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
nameColumn = new TableColumn<>("Jméno");
surnameColumn = new TableColumn<>("Příjmení");
nickColumn = new TableColumn<>("Nick");
getColumns().addAll(nameColumn, surnameColumn, nickColumn);
int columnCount = getColumns().size();
double columnSize = Math.floor(getPrefWidth() / columnCount);
nameColumn.setPrefWidth(columnSize);
nameColumn.setCellValueFactory(cdf -> cdf.getValue().nameProperty());
nameColumn.setCellFactory(TextFieldTableCell.forTableColumn());
nameColumn.setEditable(true);
surnameColumn.setPrefWidth(columnSize);
surnameColumn.setCellValueFactory(cdf -> cdf.getValue().surnameProperty());
surnameColumn.setCellFactory(TextFieldTableCell.forTableColumn());
surnameColumn.setEditable(true);
nickColumn.setPrefWidth(columnSize);
nickColumn.setCellValueFactory(cdf -> cdf.getValue().nickProperty());
nickColumn.setCellFactory(TextFieldTableCell.forTableColumn());
nickColumn.setEditable(true);
List<Teacher> list = new TeacherDao().getAllTeachers();
ObservableList<Teacher> observableList = FXCollections.observableArrayList(list);
setItems(observableList);
}
private void onEditAction(){
nameColumn.setOnEditCommit(this::updateCol);
surnameColumn.setOnEditCommit(this::updateCol);
nickColumn.setOnEditCommit(this::updateCol);
}
private void updateCol(TableColumn.CellEditEvent<Teacher, String> col) {
String newValue = col.getNewValue();
if (CheckString.isNotBlank(newValue)) {
(col.getTableView().getItems().get(
col.getTablePosition().getRow())
).setName(col.getNewValue());
Teacher teacher = (Teacher) getSelectionModel().getSelectedItem();
int id = teacher.getUser_id();
new TeacherDao().updateTeacherNick(id, newValue);
} else {
col.getTableView().refresh();
}
}
}

Elastic Search and Twitter Data example

I am learning about elastic search and I am following the next tutorial. In that tutorial it is used tweets of Twiter as example data. Method tweetJsonList return a example data. I am trying to save this in the index "tweets_juan" and type "tweet". The application run without problems, but when I search all documents using (http://localhost:9200/tweets_juan/tweet/_search?q=:) I do not found anything. Could you help me please to verify whats happens here?
public class App
{
#SuppressWarnings("unchecked")
public static void main( String[] args ) throws TwitterException, UnknownHostException
{
System.out.println( "Hello World!" );
List<String> tweetJsonList = searchForTweets();
Client client = TransportClient.builder().build()
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));
String index = "tweets_juan";
client.admin().indices()
.create(new CreateIndexRequest(index))
.actionGet();
save(client, tweetJsonList, index);
searchExample(client);
}
public static void save(Client client, List<String> tweetJsonList, String index) {
BulkRequestBuilder bulkRequestBuilder = client.prepareBulk().setRefresh(true);
for (String data : tweetJsonList) {
String indexName = index;
String typeName = "tweet";
String json = new Gson().toJson(data);
System.out.println("Juan Debug:" + data);
bulkRequestBuilder.add(client.prepareIndex(indexName, typeName).setSource(json));
}
bulkRequestBuilder.execute().actionGet();
}
public static void searchExample(Client client) {
BoolQueryBuilder queryBuilder = QueryBuilders
.boolQuery()
.must(termsQuery("text", "Baloncesto"));
SearchResponse searchResponse = client.prepareSearch("tweets_juan")
.setQuery(queryBuilder)
.setSize(25)
.execute()
.actionGet();
}
public static List searchForTweets() throws TwitterException {
Twitter twitter = new TwitterFactory().getInstance();
Query query = new Query("mundial baloncesto");
List tweetList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
QueryResult queryResult = twitter.search(query);
tweetList.addAll(queryResult.getTweets());
if (!queryResult.hasNext()) {
break;
}
query = queryResult.nextQuery();
}
Gson gson = new Gson();
return (List) tweetList.stream().map(gson::toJson).collect(Collectors.toList());
}
}
You need to put more information before anyone can answer your question.
Since you are not using any explicit mapping your fields must be getting analyzed by default. So your text field will get tokenized into multiple terms.
Use "match all" query to see what data has been indexed.
Term query is used for exact match ( including exact case) and you are trying to run term query on an analyzed field "text" which will not work.
Try using match or match phrase query on the text field and see if you get back any result.

Lucene.net Negation clause is not working

I am very much new to Lucene.net and though I am not able to achieve basic functionality i.e. Not in.
My requirement is to search "road?construction" without "Works" word.
e.g.
Main Road Construction Works -- Invalid
Road Construction And Maintenance Services -- Valid (Doesn't contains word Works)
Please refer my code below.
string searchQuery = "\"road?construction\"*";
BooleanQuery query2 = new BooleanQuery();
Query query;
try
{
query = parser.Parse(searchQuery.Trim());
}
catch (ParseException)
{
query = parser.Parse(QueryParser.Escape(searchQuery.Trim()));
}
query2.Add(query,Occur.SHOULD);
query2.Add(new BooleanClause(new TermQuery (new Term("Name", "Works")), Occur.MUST_NOT));
This still gets both above mentioned record in to search result. I wish to cut invalid record(first).
Here is the result query generated in backend.
Please suggest workaround.
Thanks in advanced.
Not sure why your putting wildcard characters into the phrase. If you're looking for "road construction" then that's all you need. If you are looking to allow some variations then maybe a "slop phrase" is what you need ie. "road construction"~2. The number part allows for n "operations" like n additional words inbetween.
Here's a set of tests that show your examples (TestExpr2, TestExpr3) and some working variations (TestExpr1 and TestQuery).
Hope this helps
[TestClass]
public class UnitTest7
{
[TestMethod]
public void TestExpr1()
{
TestExpr("\"road construction\" -works");
}
[TestMethod]
public void TestExpr2()
{
TestExpr("\"road?construction\"* -works");
}
[TestMethod]
public void TestExpr3()
{
TestExpr(QueryParser.Escape("\"road?construction\"* -works"));
}
private void TestExpr(string expr)
{
var writer = CreateIndex();
Add(writer, "Main Road Construction Works");
Add(writer, "Road Construction And Maintenance Services");
writer.Flush(true, true, true);
var searcher = new IndexSearcher(writer.GetReader());
var result = Search(searcher, expr);
Assert.AreEqual(1, result.Count);
Assert.IsTrue(result.Contains("Road Construction And Maintenance Services"));
writer.Dispose();
}
[TestMethod]
public void TestQuery()
{
var writer = CreateIndex();
Add(writer, "Main Road Construction Works");
Add(writer, "Road Construction And Maintenance Services");
writer.Flush(true, true, true);
var searcher = new IndexSearcher(writer.GetReader());
var query = new BooleanQuery();
var p = new PhraseQuery();
p.Add(new Term("name", "road"));
p.Add(new Term("name", "construction"));
query.Add(p, Occur.MUST);
query.Add(new TermQuery(new Term("name", "works")), Occur.MUST_NOT);
var result = Search(searcher, query);
Assert.AreEqual(1, result.Count);
Assert.IsTrue(result.Contains("Road Construction And Maintenance Services"));
writer.Dispose();
}
private List<string> Search(IndexSearcher searcher, string expr)
{
var analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_30);
var queryParser = new QueryParser(Lucene.Net.Util.Version.LUCENE_30, "name", analyzer);
var query = queryParser.Parse(expr);
return Search(searcher, query);
}
private List<string> Search(IndexSearcher searcher, Query query)
{
var collector = TopScoreDocCollector.Create(10, true);
searcher.Search(query, collector);
var result = new List<string>();
var matches = collector.TopDocs().ScoreDocs;
foreach (var item in matches)
{
var id = item.Doc;
var doc = searcher.Doc(id);
result.Add(doc.GetField("name").StringValue);
}
return result;
}
IndexWriter CreateIndex()
{
var directory = new RAMDirectory();
var analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_30);
var writer = new IndexWriter(directory, analyzer, new IndexWriter.MaxFieldLength(1000));
return writer;
}
void Add(IndexWriter writer, string text)
{
var document = new Document();
document.Add(new Field("name", text, Field.Store.YES, Field.Index.ANALYZED));
writer.AddDocument(document);
}
}

Adding reminder to event fails in Android

I have a method which adds an reminder to an event, but it fails:
FATAL EXCEPTION: main
android.database.sqlite.SQLiteException
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:184)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:140)
at android.content.ContentProviderProxy.insert(ContentProviderNative.java:420)
at android.content.ContentResolver.insert(ContentResolver.java:864)
at de.appwege.droid.medwege.navigationdrawer.TerminFragment.insertReminder(TerminFragment.java:848)
The method in question:
public long insertReminder(long eventID, int minutes){
ContentResolver cr = getActivity().getContentResolver();
ContentValues values = new ContentValues();
values.put(CalendarContract.Reminders.MINUTES, minutes);
values.put(CalendarContract.Reminders.EVENT_ID, eventID);
values.put(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_ALERT);
Uri uri = cr.insert(CalendarContract.Reminders.CONTENT_URI, values);
return Long.valueOf(uri.getLastPathSegment());
}
What I am missing here? both eventID and minutes are defined...
Recently, I also faced same issue. Finally, I found the solution.
First of all, you have to find all logged in gmail id from the device and then select any one gmail account and find its calendar id. After that you have to pass that id to the event query like this....
values.put(Events.CALENDAR_ID, calendarId);
at last call you function
public long insertReminder(long eventID, int minutes){
ContentResolver cr = getActivity().getContentResolver();
ContentValues values = new ContentValues();
values.put(CalendarContract.Reminders.MINUTES, minutes);
values.put(CalendarContract.Reminders.EVENT_ID, eventID);
values.put(CalendarContract.Reminders.METHOD,
CalendarContract.Reminders.METHOD_ALERT);
Uri uri = cr.insert(CalendarContract.Reminders.CONTENT_URI, values);
return Long.valueOf(uri.getLastPathSegment());
}
See below method for finding email id's...
public static Hashtable listCalendarId(Context context) {
try {
if (haveCalendarReadWritePermissions((Activity) context)) {
String projection[] = {"_id", "calendar_displayName"};
Uri calendars;
calendars = Uri.parse("content://com.android.calendar/calendars");
ContentResolver contentResolver = c.getContentResolver();
Cursor managedCursor = contentResolver.query(calendars, projection, null, null, null);
if (managedCursor.moveToFirst()) {
String calName;
String calID;
int cont = 0;
int nameCol = managedCursor.getColumnIndex(projection[1]);
int idCol = managedCursor.getColumnIndex(projection[0]);
Hashtable<String, String> calendarIdTable = new Hashtable<>();
do {
calName = managedCursor.getString(nameCol);
calID = managedCursor.getString(idCol);
Log.v(TAG, "CalendarName:" + calName + " ,id:" + calID);
calendarIdTable.put(calName, calID);
cont++;
} while (managedCursor.moveToNext());
managedCursor.close();
return calendarIdTable;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

Resources