How to use graph.getVertices() get specific vertices.
My Class name is Station has Extended V(Vertex) .
category' (datatype is LINK)is property of Station
Category's can be '#12:13' or '#12:14' or '#12:15'
I want to use graph.getVertices() JAVA to get specific category.
Something like :
graph.getVertices("Station category = '#12:13'");
graph.getVertices("Excluded Station Category = '#12:13'");
Any suggestion?
I used this simple structure to try your case (category is of type LINK):
CLASSES:
and I retrieved the results you're looking for with this code:
JAVA CODE:
package yourPackage;
import java.io.IOException;
import com.orientechnologies.orient.client.remote.OServerAdmin;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
public class YourClass{
private static String remote = "remote:localhost/";
public static void main(String[] args) {
String DBname = "yourDBname";
String currentPath = remote + DBname;
OServerAdmin serverAdmin;
try {
serverAdmin = new OServerAdmin(currentPath).connect("root", "root");
if (serverAdmin.existsDatabase()) {
OrientGraph g = new OrientGraph(currentPath);
String yourRid = "#13:0";
Iterable<Vertex> targets = g.getVerticesOfClass("Station");
System.out.println("Category #rid = " + yourRid);
System.out.println();
for (Vertex target : targets) {
Vertex category = target.getProperty("category");
if (category.getId().toString().equals(yourRid)) {
System.out.println("Matched Station: " + target.getProperty("name") + " Category: "
+ category.getProperty("name") + " (" + category.getId() + ")");
System.out.println();
} else {
System.out.println("Excluded Station: " + target.getProperty("name") + " Category: "
+ category.getProperty("name") + " (" + category.getId() + ")");
}
}
}
else {
System.out.println("Database " + DBname + " not found");
}
serverAdmin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
OUTPUT:
Category #rid = #13:0
Matched Station: First Category: category 1 (#13:0)
Excluded Station: Second Category: category 2 (#13:1)
Excluded Station: Third Category: category 3 (#13:2)
Hope it helps
to get all vertices of Station class, try:
g.V('_class','Station')
or to filter by a category field
g.V('_class','Station').has('category','catvalue 123')
or if you have multiple to match:
g.V('_class', 'Station').has('category', T.in,['12:13','12:14'])
or for specific Id
g.v('12:13')
to find if an edge exists between 2 vertices, you can use:
g.v(stationVtxId).outE('edge_label').sideEffect{x=it}.inV.filter{it == g.v(catVtxId)}.back(2)
I used an index on the property category of the class Station
create class Station extends V
create class Category extends V
create property Station.name STRING
create property Station.category LINK Category
create property Category.name STRING
create index Station.category ON Station (category) NOTUNIQUE
insert into category(name) values ("category A") // 13:0
insert into category(name) values ("category B") // 13:1
insert into Station(name,category) values ("Station 1",#13:0)
insert into Station(name,category) values ("Station 2",#13:1)
JAVA
Related
I am having an arraylist fetching name and status of a person. Arraylist is storing the status and name. Its displaying one name at a time. How can I be able to display multiple names at once in alert dialog?
private ArrayList getunfiledRogspDoctorList() {
SqlDataStore sd = new SqlDataStore(this);
sd.open();
String gspQuery = " SELECT * FROM "+ TABLE_DOCTOR + " WHERE " + Queryclass.DOCTOR_ROGSP_STATUS + " == " + 0 + " AND " + Queryclass.DOCTOR_DATE_ID + " = '" + selectionID + "'";
Cursor gspCu = sd.getData(gspQuery);
if(gspCu.moveToFirst()){
do {
rogspname = gspCu.getString(gspCu.getColumnIndex(Queryclass.DOCTOR_CONTACTNAME));
unfiledrogspDoctorList.add(gspCu.getString(gspCu.getColumnIndex(Queryclass.DOCTOR_ROGSP_STATUS)) + rogspname);
}while (gspCu.moveToNext());
}
gspCu.close();
sd.close();
System.out.println("unfiledrogspDoctorList "+unfiledrogspDoctorList);
return unfiledrogspDoctorList;
}
From the code, you are having an ArrayList of your target display String in unfiledrogspDoctorList:
// Suggest to also define the type of your returning ArrayList
private ArrayList<String> getunfiledRogspDoctorList() {
// Define a local ArrayList
ArrayList<String> unfiledrogspDoctorList = new ArrayList<>();
SqlDataStore sd = new SqlDataStore(this);
sd.open();
String gspQuery = " SELECT * FROM "+ TABLE_DOCTOR + " WHERE " + Queryclass.DOCTOR_ROGSP_STATUS + " == " + 0 + " AND " + Queryclass.DOCTOR_DATE_ID + " = '" + selectionID + "'";
Cursor gspCu = sd.getData(gspQuery);
if(gspCu.moveToFirst()){
do {
rogspname = gspCu.getString(gspCu.getColumnIndex(Queryclass.DOCTOR_CONTACTNAME));
unfiledrogspDoctorList.add(gspCu.getString(gspCu.getColumnIndex(Queryclass.DOCTOR_ROGSP_STATUS)) + rogspname);
}while (gspCu.moveToNext());
}
gspCu.close();
sd.close();
System.out.println("unfiledrogspDoctorList "+unfiledrogspDoctorList);
return unfiledrogspDoctorList;
}
You can consider to convert your ArrayList of String into just a String.
private String concat(ArrayList<String> unfiledrogspDoctorList) {
StringBuilder sb = new StringBuilder();
for (String item : unfiledrogspDoctorList) {
sb.append(item);
sb.append(","); // Or change into other separate you would like to display
}
sb.setLength(Math.max(0, sb.length() - 1)); // Remove the appending character
return sb.toString();
}
Then you can make use of an AlertDialog to display that concatenated String.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder
.setMessage(concat(getunfiledRogspDoctorList()))
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Do anything upon pressing OK button
}
);
AlertDialog alert = builder.create();
alert.show();
You could use :-
SELECT group_concat(name) FROM ....
or to place each on a line you could change the default comma separator to a line feed using
SELECT group_concat(name,'\n') FROM ....
.... representing the rest of the SQL in the question
See https://www.sqlite.org/lang_aggfunc.html#group_concat
note that the GROUP as no GROUP BY clause is provided is a single group (and therefore output row) made up of ALL extracted rows.
Hey I have a problem with accessing the data from a Cursor in Android Studio.
I have two tables in the database events and messages. So each event in the events table may have multiple messages in the messages table. The event and its messages share a common event_id.
I am using LoaderCallbacks to get a Cursor from a ContentProvider. In the ContentProvider query method, I am using a rawQuery to INNER JOIN these two tables.
In this example I query for an event which shares its event_id with two messages from the message table. In the ContentProvider the rawQuery() method with the INNER JOIN was performed.
At this state I can see in the Debugger that the variable mCount from the Cursor is -1. I am not sure what this means but anyways, back in the onLoadFinish() method the Cursor now contains a variable mCursor and this variable again contains a variable mCount which is 2. Which makes sense, since the query should return a Cursor with two rows and since there are two messages. But now I try to get a String with the getString() method and the CursorIndexOutOfBoundsException: Index -1 requested, with a size of 2 is thrown.
I realy don't understand what this means. And I don't find any hint in die Cursor docs, what it means when mCount is -1.
Furthermore in the onLoadFinished method the variable mEditTable is null. And in other queries where I don't join anything it always contains a table.
I am quite sure that the issue somwhere lays with the INNER JOIN, since everything works fine if I use just a query method inside the ContentProvider.query method. But I don't know what I should do differently. I hope you might help me with this. I am aware that, if there is no message related to an event, this query will return an empty cursor with mCount = 0 and then again an exception will be thrown. But this is not the case in this example.
EventProvider class:
public class EventProvider extends ContentProvider {
private static final String LOG_TAG = EventProvider.class.getSimpleName();
private static final int EVENTS = 100;
private static final int EVENT_ID = 101;
private static final int EVENT_MESSAGE_ID = 102;
private static UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
private EventDbHelper mEventDbHelper;
static {
sUriMatcher.addURI(EventContract.CONTENT_AUTHORITY, EventContract.PATH_EVENTS, EVENTS);
sUriMatcher.addURI(EventContract.CONTENT_AUTHORITY, EventContract.PATH_EVENTS + "/#", EVENT_ID);
sUriMatcher.addURI(EventContract.CONTENT_AUTHORITY, EventContract.PATH_EVENT_AND_ITS_MESSAGES + "/#", EVENT_MESSAGE_ID);
}
#Override
public boolean onCreate() {
mEventDbHelper = new EventDbHelper(getContext());
return true;
}
#Nullable
#Override
public Cursor query(#NonNull Uri uri, #Nullable String[] projection, #Nullable String selection, #Nullable String[] selectionArgs, #Nullable String sortOrder) {
SQLiteDatabase database = mEventDbHelper.getReadableDatabase();
Cursor retCursor;
final int match = sUriMatcher.match(uri);
switch (match) {
case EVENTS:
retCursor = database.query(EventEntry.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);
break;
case EVENT_ID:
selection = EventEntry.COLUMN_EVENT_ID + "=?";
selectionArgs = new String[] {String.valueOf(ContentUris.parseId(uri))};
retCursor = database.query(EventEntry.TABLE_NAME, projection,selection, selectionArgs, null, null, sortOrder);
break;
case EVENT_MESSAGE_ID:
selection = MessageEntry.TABLE_NAME + "." + MessageEntry.COLUMN_EVENT_ID + "=?";
selectionArgs = new String[] {String.valueOf(ContentUris.parseId(uri))};
StringBuilder sqlQuery = new StringBuilder();
sqlQuery.append("SELECT ");
if(projection != null && projection.length > 0) {
for(String s: projection) {
sqlQuery.append(s).append(", ");
}
}
sqlQuery.replace(sqlQuery.length()-2, sqlQuery.length(), " FROM ").append(MessageEntry.TABLE_NAME);
sqlQuery.append(" INNER JOIN ").append(EventEntry.TABLE_NAME).append(" ON ");
sqlQuery.append(EventEntry.TABLE_NAME).append(".").append(EventEntry.COLUMN_EVENT_ID).append("=");
sqlQuery.append(MessageEntry.TABLE_NAME).append(".").append(MessageEntry.COLUMN_EVENT_ID);
sqlQuery.append(" WHERE ").append(selection).append(" ORDER BY ").append(sortOrder).append(";");
Log.v(LOG_TAG, "SQL command for: " + uri.toString());
Log.v(LOG_TAG, sqlQuery.toString());
retCursor = database.rawQuery(sqlQuery.toString(), selectionArgs);
break;
default:
throw new IllegalArgumentException("Cannot query unknown URI: " + uri);
}
retCursor.setNotificationUri(getContext().getContentResolver(), uri);
return retCursor;
}
EventActivity:
#NonNull
#Override
public Loader<Cursor> onCreateLoader(int id, #Nullable Bundle args) {
String[] projection = {
MessageEntry.TABLE_NAME + "." + MessageEntry.COLUMN_EVENT_ID,
MessageEntry.TABLE_NAME + "." + MessageEntry.COLUMN_SENDER,
MessageEntry.TABLE_NAME + "." + MessageEntry.COLUMN_DATE,
MessageEntry.TABLE_NAME + "." + MessageEntry.COLUMN_MESSAGE,
EventEntry.TABLE_NAME + "." + EventEntry._ID,
EventEntry.TABLE_NAME + "." + EventEntry.COLUMN_NAME,
EventEntry.TABLE_NAME + "." + EventEntry.COLUMN_DATE,
EventEntry.TABLE_NAME + "." + EventEntry.COLUMN_DATE_ADDENDUM,
EventEntry.TABLE_NAME + "." + EventEntry.COLUMN_CONTACT,
EventEntry.TABLE_NAME + "." + EventEntry.COLUMN_STATUS,
EventEntry.TABLE_NAME + "." + EventEntry.COLUMN_PICTURE_NAME,
EventEntry.TABLE_NAME + "." + EventEntry.COLUMN_DESCRIPTION,
EventEntry.TABLE_NAME + "." + EventEntry.COLUMN_STREET,
EventEntry.TABLE_NAME + "." + EventEntry.COLUMN_HOUSE_NUMBER,
EventEntry.TABLE_NAME + "." + EventEntry.COLUMN_POST_CODE,
EventEntry.TABLE_NAME + "." + EventEntry.COLUMN_CITY,
EventEntry.TABLE_NAME + "." + EventEntry.COLUMN_EMAIL,
EventEntry.TABLE_NAME + "." + EventEntry.COLUMN_LOCATION,
EventEntry.TABLE_NAME + "." + EventEntry.COLUMN_SIGNED_UP
};
String sortOrder = MessageEntry.COLUMN_DATE + " DESC";
return new CursorLoader(this, mCurrentEventUri, projection, null, null, sortOrder);
}
#Override
public void onLoadFinished(#NonNull Loader<Cursor> loader, Cursor cursor) {
int indexName = cursor.getColumnIndex(EventEntry.COLUMN_NAME);
int indexImage = cursor.getColumnIndex(EventEntry.COLUMN_PICTURE_NAME);
String imageName = cursor.getString(indexImage); //Here the Exception is thrown
mEventName.setText(cursor.getString(indexName));
mEventAdapter.swapCursor(cursor);
}
If you need something else, I will upload it.
Thanks.
CursorIndexOutOfBoundsException: Index -1 requested, with a size of 2
-1 with Cursors will generally be 1 of 2 issues :-
that the column name passed to getColumnIndex is not a name of a column in the output.
that the Cursor is at the beginning that is at the position that is "before the first row", as is the case when a Cursor is returned.
I suspect that your issue is due to 2 as I believe the message indicates the row of the column.
2 can happen if a move???? (e.g. moveToFirst, moveToNext) method was not actioned (I cannot see any such move in your code) or that the result was not checked (the move methods return true or false to indicate whether or not the move request could be satisfied).
see (probably moveToFirst)
https://developer.android.com/reference/android/database/Cursor#move(int)
https://developer.android.com/reference/android/database/Cursor#moveToFirst()
https://developer.android.com/reference/android/database/Cursor#moveToLast()
https://developer.android.com/reference/android/database/Cursor#moveToNext()
https://developer.android.com/reference/android/database/Cursor#moveToPosition(int)
https://developer.android.com/reference/android/database/Cursor#moveToPrevious()
The fix would be to move the Cursor to a row, checking if the move was actually successful and to then extract the data.
e.g.
String imageName = "No Image"
if (cursor.moveToFirst() && indexImage > -1) {
imageName = cursor.getString(indexImage); //Here the Exception is thrown
}
The above, && indexImage > -1, would also weed out the situation where the column name does not exist in the Cursor.
I have the following defined as a native query in a repository (dispenseRepository) :
#Query(
value = "SELECT p.*, c.*, s.*, d.* from patient p, consult c ,script s,dispense d "
+ " where p.patient_id=c.patient_id "
+ " and c.consult_id = d.consult_id "
+ " and c.fk_script_id =s.script_id"
+ " and c.consult_id=?1 ",
nativeQuery = true
)
List<Dispense> findInvoiceByConsultId(Long consultId);
The Rest Controller has :
#RequestMapping(value = "/api/invoice/{consultId}",method = {RequestMethod.GET})
public List<Dispense> invoice(#PathVariable(value="consultId")Long consultId){
return dispenseRepository.findInvoiceByConsultId(consultId);
}
When I hit the api I only get dispense details:
[
{
"dispenseId": 1,
"icd10": "J.10",
"tariffCode": "10010",
"dispenseItem": "Lenses",
"price": 400.0
},
{
"dispenseId": 3,
"icd10": "J.10",
"tariffCode": "111000",
"dispenseItem": "Other",
"price": 1500.0
},
{
"dispenseId": 4,
"icd10": "K.100",
"tariffCode": "10010",
"dispenseItem": "Eye Test",
"price": 550.0
}
]
I'd like all the data as per query which will be used for Jasper report
patient-consult 1-M
consult-script 1-1
consult-dispense 1-M
Since in your query you return all fields from all tables: SELECT p.*, c.*, s.*, d.* from patient p, consult c ,script s,dispense d creating projections/DTOs for so many objects and fields is very cumbersome. There are 2 ways to proceed. Either specify exactly the fields you want from each table in your query and create a DTO to hold those fields.
e.g.
Approach 1:
I chose only one field from each table to make it as example. Please not that you have to convert your query from native to jpa one!
#Query("SELECT new com.example.demo.ResultDTO(p.patientName, c.reservationNumber, s.addition, d.dispenseItem) from Patient p, Consult c, Script s, Dispense d ...")
List<ResultDTO> findInvoiceByConsultId(Long consultId);
and ResultDTO class can be:
package com.example.demo;
public class ResultDTO {
private String patientName;
private String reservationNumber;
private String addition;
private String dispenseItem;
public ResultDTO(String patientName, String reservationNumber, String addition, String dispenseItem) {
this.patientName = patientName;
this.reservationNumber = reservationNumber;
this.addition = addition;
this.dispenseItem = dispenseItem;
}
public String getPatientName() {
return patientName;
}
public void setPatientName(String patientName) {
this.patientName = patientName;
}
public String getReservationNumber() {
return reservationNumber;
}
public void setReservationNumber(String reservationNumber) {
this.reservationNumber = reservationNumber;
}
public String getAddition() {
return addition;
}
public void setAddition(String addition) {
this.addition = addition;
}
public String getDispenseItem() {
return dispenseItem;
}
public void setDispenseItem(String dispenseItem) {
this.dispenseItem = dispenseItem;
}
}
UPDATE
Approach 1 won't work with a nativeQuery, you have to convert it to jpa one so unless you convert your query to jpql, the above code wont work.
OR the much easier but bulkier, keep the query as is and place the result on a List of Maps.
Approach 2:
#Query(
value = "SELECT p.*, c.*, s.*, d.* from patient p, consult c ,script s,dispense d "
+ " where p.patient_id=c.patient_id "
+ " and c.consult_id = d.consult_id "
+ " and c.fk_script_id =s.script_id"
+ " and c.consult_id=?1 ",
nativeQuery = true
)
List<Map<String, Object>> findInvoiceByConsultId(Long consultId);
I'm new to Spring and i have an issue with the following query:
String rejected_offer_query = "SELECT b.job_instance_id, b.start_time, count (*) " +
"FROM SygaOfferRejected s , BatchJobExecution b, BatchJobInstance bi "+
"where s.heure_debut = b.start_time " +
"and s.heure_fin = b.end_time " +
"and b.job_execution_id = bi.job_instance_id " +
"and bi.job_name = :batchName "+
"and b.status = :batchStatus " +
"group by b.job_instance_id";
It doesn't return data, but it should return one row as a result: (Test made directly with MySql).
I think it's an inheritance problem because when i try to execute the same query with a super class it works :
SELECT b.job_instance_id, b.start_time, count (*) " +
"FROM SygaOffer s , BatchJobExecution b, BatchJobInstance bi "+
"where s.heure_debut = b.start_time " +
"and s.heure_fin = b.end_time " +
"and b.job_execution_id = bi.job_instance_id " +
"and bi.job_name = :batchName "+
"and b.status = :batchStatus " +
"group by b.job_instance_id"
The SygaOfferRejected class extends the SygaOffer, here's the source code;
#Entity
#Inheritance
#Table(name = "bob_syga_off")
public class SygaOffer {
#Id
private long id_offre;
private String acteur;
private String heure_debut;
private String heure_fin;
private String reference_offre;
private int retry;
}
------------------------------------------
#Entity
#Table(name ="bob_syga_offr_rejected")
public class SygaOfferRejected extends SygaOffer{
}
The inheritance strategy is the issue i should specify the TABLE_PER_CLASS type in the parent class :
#Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
Hope that helps ;)
I want to print in the Java console shortestpath between two vertices. I can not print anything or if you have any way to do that would appreciate it.
String subquery = "Select shortestpath(17:10, 17:14, BOTH) ";
Iterable<OrientVertex> result = orientDBGraph.command(new OSQLSynchQuery<OrientVertex>(subquery)).execute();
Assert.assertTrue(result.iterator().hasNext());
System.out.println(result);
for (OrientVertex d : result) {
System.out.println("Shortest path from " + ((OrientVertex) d.getProperty("$current")).getProperty("name") + " and "
+ ((Iterable<OrientVertex>) d.getProperty("$target")).iterator().next().getProperty("name") + " is: "
+ d.getProperty("path"));
}
Code:
import com.orientechnologies.orient.core.sql.OCommandSQL;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
import com.tinkerpop.blueprints.impls.orient.OrientGraphFactory;
import com.tinkerpop.blueprints.impls.orient.OrientVertex;
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
String dbName = "ytrewa";
OrientGraphFactory dbfactory = new OrientGraphFactory("remote:127.0.0.1:2424/"+dbName, "root", "root").setupPool(1, 50);
OrientGraph g = dbfactory.getTx();
try {
String query = "select expand(shortestPath) from (select shortestPath(#9:0,#9:1,BOTH))";
Iterable<OrientVertex> res = g.command(new OCommandSQL(query)).execute();
while(res.iterator().hasNext()){
OrientVertex v = res.iterator().next();
System.out.println("rid: "+v.getId().toString());
}
} finally {
g.shutdown();
}
}
}
Output:
rid: #9:0
rid: #10:0
rid: #12:0
rid: #9:1