Database Reference
In-Depth Information
Capturing Consumption
You are creating code that directly captures consumption for a user, but the process could also be done by creating a
graph-backed service to consume the webserver logs in real time or another data store to create the relationships. The
result would be the same in either event: a process that connects nodes to reveal a pattern of consumption.
For the sample application, you used the
createUserView
method, shown in Listing 11-47, in
ProductImpl
to first
find the Product entity being viewed and then create an explicit relationship type called
VIEWED
. Notice that this is the
first relationship type in the application that also contains properties. In this case, you are creating a timestamp with
a
Date
object and String value of the timestamp. Use the
getRelationshipBetween
method of the
neo4jTemplate
to
determine if the relationship already exists.
Listing 11-47.
The
createUserView
in
ProductImpl
public void
createUserView
(User user, Long productNodeId) {
Product product =
productRepository.findOne
(productNodeId);
try {
Relationship r =
neo4jTemplate.getRelationshipBetween(
user, product,
GraphStoryConstants.VIEWED
);
Long d = new Date().getTime() / 1000;
Date timestamp = new Date(d * 1000);
SimpleDateFormat dformatter = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat tformatter = new SimpleDateFormat("h:mm a");
String timestampAsStr = dformatter.format(timestamp) + " at " +
tformatter.format(timestamp);
if (r == null) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("timestamp", d);
map.put("dateAsStr", timestampAsStr);
neo4jTemplate.createRelationshipBetween
(neo4jTemplate.getNode
(user.getNodeId()), neo4jTemplate.getNode(productNodeId),
GraphStoryConstants.VIEWED, map);
} else {
r.setProperty("timestamp", d);
r.setProperty("dateAsStr", timestampAsStr);
neo4jTemplate.save
(r);
}
}
catch (Exception e) {
log.error(e);
}
}
If the result of
getRelationshipBetween
is null, a map is created with key value pairs to create properties on the
new relationship, specifically
timestamp
and
dateAsStr
. Otherwise, you can use setProperty and specify the property
names and their respective values as arguments.