How to handle conflicting types in JSON?

I am looking to store Kubernetes YAML/JSONs in dgraph. The issue is sometimes fields with same name (predicate in dgraph) have int or string data. Example:

apiVersion: v1
kind: Service
metadata:
  name: my-service
spec:
  ports:
    - protocol: TCP
      port: 80
      targetPort: 9376
apiVersion: v1
kind: Service
metadata:
  name: my-service
spec:
  ports:
    - protocol: TCP
      port: 443
      targetPort: https

In Kubernetes, which uses openapi v3, this field will defined using anyOf.

targetPort:
  anyOf:
  - type: integer
  - type: string
  description: Name or number of the port to access on
    the container. Number must be in the range 1 to 65535.
    Name must be an IANA_SVC_NAME.
  x-kubernetes-int-or-string: true

Will it be possible to store this types of JSONs in dgraph?

Dgraph can have only one type per predicate. If your predicate switches between two o more types. You should set it as a string.

1 Like

Can dgraph automatically convert types to string? Or, we are going to get error?

Hey @tamalsaha,

Dgraph would not consider the type to be of “string” by default in case of predicate having different types of values. I apologize for the previous information. It would infer the type based on the value of the predicate. So mutation like this would throw an error.

{
    "set": [
  		{
        "port": 443 
		},
      {
        "port": "http"
      }
      ]
}

For these types of predicates, I suggest you to define the type as “string” beforehand.

2 Likes

That is unfortunate given how dgraph handles all predicates in a Global namespace. Now 2 different JSON objects can’t have fields with same name but different datatype.